Send the selected option using get to another page - html

I have a dropdown select option.There is button.On clicking the button the selected option must be send to another page "update.php" so that i can access the option there.In my case the new page is not loading or getting redirected to.
<select id=31 >
<option value="pending">pending</option>
<option value="accepted">accepted</option>
<option value="in progress">in progress</option>
<option value="cant">Cant be done</option>
</select></td>
<td><button id=i31 onclick="$.get("update.php",{id:31,s:$("#31 option:selected").text();})" >Submit</button></td>

If update.php is in another directory than your HTML make sure to use the absolute path to the file.
If you want the whole page to redirect you will want to use:
<form action="update.php" method="POST">
<select id="31" name="myFormOption" >
<option value="pending">pending</option>
<option value="accepted">accepted</option>
<option value="in-progress">in progress</option>
<option value="cant">Cant be done</option>
</select>
<button type="submit">Submit</button>
</form>
And in update.php catch the incoming POST with
if(isset($_POST['myFormOption'])) {
//Process Form Here
}
If you have to use AJAX I would then use window.location.href = "http://example.com"; after the call is successful.
Hope this helps :)
EDIT: Added AJAX Script
<script>
$('#i31').on('click', function() {
$.ajax({
method: 'GET',
url: 'update.php',
data: { id: 31, s: $("#31 option:selected").val() },
success: function() {
window.location.href = "http://example.com";
}
});
});
</script>

Related

Is it possible to do <select> with links opening after clicking submit?

Is it even possible to do select with links that when you click submit button it will move you to the selected website, for example
<form>
<select>
<option value="1"> test 1 </option>
<option value="http://www.google.com"> google.com </option>
<option value="http://www.youtube.com"> youtube.com </option>
<option value="http://www.facebook.com"> facebook.com </option>
</select>
<input type="submit">
//when submit clicked, and you choosed any option then you will be moved to this website
</form>
Yes, it possible to have a <select> element with links opening after clicking submit.
In order to do so, add the following JavaScript code:
const submitButton = document.querySelector("[type=submit]")
const select = document.querySelector("select")
submitButton.addEventListener("click", function (e) {
e.preventDefault()
window.location.href = select.value
})
Using a bit of javascript you could add a change handler to the select that navigates the user to the value of the selected option.
Note that this may not work within the stackoverflow demo frame, but should be fine on your site.
document.querySelector('select').addEventListener('change', (e) => {
document.location.href = e.target.value;
});
<select>
<option value="1" id="1"> test 1 </option>
<option value="https://www.google.com" id="http://www.google.com"> google.com </option>
<option value="https://www.youtube.com" id="http://www.youtube.com"> youtube.com </option>
<option value="https://www.facebook.com" id="http://www.facebook.com"> facebook.com </option>
</select>

Make "name" not appear on url using a <select>

I'm writing a simple form, but I've encountered a problem. The form must generate an url like this
https://website.com/properties/hotelvinadelmar?locale=es&check_in_date=22-03-2019&check_out_date=25-03-2019&number_adults=4&number_children=9
The part after /properties/ (in this case, "hotelvinadelmar") is a code for an especific hotel, while the rest is the information the customer provide to check if there's availability.
I wrote this form:
Sucursal: <br>
<select name="test" id="id" required>
<option value="hotelvinadelmar?locale=es">Viña del Mar</option>
<option value="hotelsantiago1?locale=es">Nueva Providencia</option>
<option value="hotelsantiago2?locale=es">Providencia</option></select>
<br><br>
</select>
this almost work, but generates an url like this (...)/properties/?test=hotelvinadelmar?locale=es&number_adults=1(...)
Which is creating an url structured like this
[form action (the url I entered)][Option Name][selected Option Value]
But the thing must be like this
[form action (the url I entered)][selected Option Value]
How can this be achieved? Thanks in advance!
this is the correct behavior because the submitted form data test=hotelvinadelmar will be added after the URL
(...)/properties/, in order the achieve the desired result you can try to add action attribute to your form as <form action="/hotel"> and change the select as:
<select name="hotelname" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
<br><br>
</select>
the generated link will be: (...)/properties/hotel?name=hotelvinadelmar(...)
or you can use a javascript function with onSubmit event, for example:
<script>
function submitForm(){
var hotelName = document.getElementById('hotelName').value;
var param1Value = document.getElementById('id').value;
switch(hotelName) {
case 'hotelvinadelmar':
window.location.href = '/hotelvinadelmar?param1=' + param1Value + '&param2=' + (...);
break;
case 'hotelsantiago1':
window.location.href = '/hotelsantiago1?param1=' + param1Value;
break;
}
// stop submit
return false;
}
</script>
<form onsubmit="submitForm()" method="get">
<select id="hotelName" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option></select>
</select>
<input type="submit" value="submit"/>
</form>
Capture the submission event and update the form action attribute to append the hotel name to the submission path:
document.forms[0].addEventListener("submit", function (evt) {
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
});
You'll need remove the locale property from your select input. Simply add a hidden form element (or selectable option) to your form:
<input type="hidden" name="locale" value="es">
An example url:
https://website.com/properties/hotelvinadelmar?locale=es&hotelname=hotelvinadelmar&val1=one&val2=two
Here's a demonstration how the form action attribute can be updated:
document.forms[0].addEventListener("submit", function (evt) {
evt.preventDefault(); // demonstration only
let ff = evt.target;
ff.action = "/properties/" + ff.hotelname.options[ff.hotelname.selectedIndex].value;
console.log(ff.action); // demonstration only
return false; // demonstration only
});
<form action="/properties/" method="get">
<input type="hidden" name="locale" value="es">
Sucursal:
<select name="hotelname" id="id" required>
<option value="hotelvinadelmar">Viña del Mar</option>
<option value="hotelsantiago1">Nueva Providencia</option>
<option value="hotelsantiago2">Providencia</option>
</select>
<input type="hidden" name="val1" value="one">
<input type="hidden" name="val2" value="two">
<input type="submit">
</form>

Pass html control values in Url.Action: MVC

I want to pass two parameters in #Url.Action.
View:
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="button" id="btnDownload">Download</button>
<button type="button" id="btnSearch">Search</button>
On Download button click, I am calling the method "ExportToExcel" in Masters Controller and also I need to pass two parameters. i.e. the selected value of select html and textbox value.
Now, I am using like below;
<button type="button" id="btnDownload" onclick="location.href='#Url.Action("ExportToExcel", "Masters", new { ddlSearchBy = #TempData["ddlSearchBy"], txtSearchValue = #TempData["txtSearchValue"] })'">Download</button>
Can I directly pass the html control values in #Url.Action?
Edited:
Controller:
[HttpPost]
public ActionResult ExportToExcel(string ddlSearchBy, string txtSearchValue)
{
var grid = new GridView();
grid.DataSource = from data in GetTaxMasterTable(ddlSearchBy, txtSearchValue)
select new
{
Code = data.taxCode,
TaxDescription = data.taxDescription,
ClassDescription = data.classDescription,
Location = data.locationShortName,
Zone = data.zoneName,
TaxValue = data.taxValue,
Tax = data.taxPercentage,
ModifiedDate = data.modifiedDate
};
grid.DataBind();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename = TaxMaster.xls");
Response.ContentType = "application/vnd.ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
return RedirectToAction("TaxMaster");
}
jQuery:
$("#btnSubmitDownloadExcel").click(function (e) {
var ddlSearchBy = $("#ddlSearchBy").val();
var txtSearchValue = $("#txtSearchValue").val();
$.ajax({
type: "POST",
url: "/Masters/ExportToExcel",
data: JSON.stringify({ "ddlSearchBy": ddlSearchBy, "txtSearchValue": txtSearchValue }),
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
alert("err");
alert(JSON.stringify(data));
}
});
});
This code is not downloading the Excel.
You cannot pass values from input elements using regular hyperlinks (Url.Action) without resorting to javascript.
But you can simply use a form with a method of GET.
<form action="Masters/ExportToExcel" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnDownload">Download</button>
</form>
Might want to use the Html.BeginForm() helper to generate the form for a more cleaner code, but the end result is the same.
Update - If you already have a form with another submit action
If you don't need to support IE 9 or below, you can use the formaction attribute to have the button change the action of the form.
Example:
<form action="SomeController/Search" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnSearch">Search</button>
<button type="submit" id="btnDownload" formaction="Masters/ExportToExcel">Download</button>
</form>
In this example, the form will do a get by default on SomeController/Search, when you click the btnSearch button. However, if you click the btnDownload button, the form will do a get request to Masters/ExportToExcel.
If you need to support IE below version 10, you need to use javascript to change the action of the form before you submit it.
Example using jQuery:
<form action="SomeController/Search" method="get">
<select id="ddlSearchBy" name="ddlSearchBy" style="width: 150px">
<option value="TaxCode">Tax Code</option>
<option value="TaxDescription">Tax Description</option>
<option value="ClassDescription">Class Description</option>
<option value="ZoneName">Zone Name</option>
</select>
<input type="text" name="txtSearchValue" id="txtSearchValue"/>
<button type="submit" id="btnSearch" onclick="$(this).closest('form').attr('action','SomeController/Search');">Search</button>
<button type="submit" id="btnDownload" onclick="$(this).closest('form').attr('action','Masters/ExportToExcel');">Download</button>
</form>

Filter <select> with other <select> with database mysql and php

I have a form and the user have to select the first <select> and it will filter the second <select> on db and just after show to user.
I've seen it on some sites and I would like to put it on mine
The first <select>
<select name="area" id="area">
<option title="" value="">Select ...</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">third</option>
</select>
If I select o option with value 1, it will search on MySQL all lines with id=1
SELECT * FROM tblarea WHERE id_prof = 1;
And this result will make second select
<select name="prof" id="prof">
<option title="" value="">Select ...</option>
<option value="1">1.1</option>
<option value="2">1.2</option>
<option value="3">1.3</option>
</select>
While the query is working it will show on <select> "Searching ..."
If I am thinking wrong please help me, and give me ideas.
Thanks
As #dontHaveName suggested, use an Ajax call that will look something like this:
$('#area').on('change', function(e) {
$.ajax({
url: '/jobs/options/',
type: 'POST',
data: $(e.target).val(),
dataType: 'html',
success: function(opts) {
$('#prof').html(opts);
},
error: function(xhr, status, err) {
console.log(err);
}
});
});
Some of the Ajax code is from memory, so let me know if you're getting errors.
If you have few items on your select object, I suggest you to load all possibilities into a JavaScript hash. In this case, use your PHP program to create and populate this hash. And once the user change the first select element, you call a function to populate the second select, using something like this:
<html>
<body>
<script language=JavaScript>
//new hash is created
var area_prof = new Object();
// hash is being populated
area_prof["f"] = new Array("1.1","1.2","orange");
area_prof["s"] = new Array("2.1","2.2","white");
area_prof["t"] = new Array("3.1","3.2","3.3","hello world");
function populate()
{
var value=document.getElementById("area").options[document.getElementById("area").selectedIndex].value;
while (document.getElementById("prof").options[1])
{
document.getElementById("prof").options[1] = null;
}
for (var i=0; i<area_prof[value].length; i++)
{
document.getElementById("prof").options[i+1] = new Option(area_prof[value][i],i);
}
}
</script>
<select name="area" id="area" onChange=populate()>
<option title="" value="">Select ...</option>
<option value="f">First</option>
<option value="s">Second</option>
<option value="t">third</option>
</select>
<select name="prof" id="prof">
<option title="" value="">Select ...</option>
</select>
</body>
</html>
But if you really want/need to create another http request to load the second combobox, ajax is what you need:
https://api.jquery.com/jQuery.ajax/
Best regards,
Eduardo Maia

Redirect on select option in select box

At the moment I am using this:
<select ONCHANGE="location = this.options[this.selectedIndex].value;">
it redirect me on the location inside of the option value. But it doesn't work as expected .. mean that if I click on the first option of the select, then onChange action not running. I was thinking about javascript, but I think you'll have some better suggestions guys. So how can I make it work if I click on each option it'll redirect me to the it's value?
Because the first option is already selected, the change event is never fired. Add an empty value as the first one and check for empty in the location assignment.
Here's an example:
https://jsfiddle.net/bL5sq/
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://google.com">Google</option>
<option value="https://yahoo.com">Yahoo</option>
</select>
I'd strongly suggest moving away from inline JavaScript, to something like the following:
function redirect(goto){
var conf = confirm("Are you sure you want to go elswhere?");
if (conf && goto != '') {
window.location = goto;
}
}
var selectEl = document.getElementById('redirectSelect');
selectEl.onchange = function(){
var goto = this.value;
redirect(goto);
};
JS Fiddle demo (404 linkrot victim).
JS Fiddle demo via Wayback Machine.
Forked JS Fiddle for current users.
In the mark-up in the JS Fiddle the first option has no value assigned, so clicking it shouldn't trigger the function to do anything, and since it's the default value clicking the select and then selecting that first default option won't trigger the change event anyway.
Update:
The latest example's (2017-08-09) redirect URLs required swapping out due to errors regarding mixed content between JS Fiddle and both domains, as well as both domains requiring 'sameorigin' for framed content. - Albert
to make it as globally reuse function using jquery
HTML
<select class="select_location">
<option value="http://localhost.com/app/page1.html">Page 1</option>
<option value="http://localhost.com/app/page2.html">Page 2</option>
<option value="http://localhost.com/app/page3.html">Page 3</option>
</select>
Javascript using jquery
$('.select_location').on('change', function(){
window.location = $(this).val();
});
now you will able to reuse this function by adding .select_location class to any Select element class
For someone who doesn't want to use inline JS.
<select data-select-name>
<option value="">Select...</option>
<option value="http://google.com">Google</option>
<option value="http://yahoo.com">Yahoo</option>
</select>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded',function() {
document.querySelector('select[data-select-name]').onchange=changeEventHandler;
},false);
function changeEventHandler(event) {
window.location.href = this.options[this.selectedIndex].value;
}
</script>
This can be archived by adding code on the onchange event of the select control.
For Example:
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value=""></option>
<option value="http://google.com">Google</option>
<option value="http://gmail.com">Gmail</option>
<option value="http://youtube.com">Youtube</option>
</select>
{{-- dynamic select/dropdown --}}
<select class="form-control m-bot15" name="district_id"
onchange ="location = this.options[this.selectedIndex].value;"
>
<option value="">--Select--</option>
<option value="?">All</option>
#foreach($location as $district)
<option value="?district_id={{ $district->district_id }}" >
{{ $district->district }}
</option>
#endforeach
</select>
<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
<option value="">Select...</option>
<option value="https://reactjs.org/">React Js</option>
<option value="https://angularjs.org/">Angular Js</option>
</select>