Put data into textboxes when item is selected in combobox - javascript

I have a combobox with a name and ID of "device". When a device is selected from the combobox e.g. "iPhone 1st Gen", I want a text field with a name and ID of "processor" to fill with the processor name e.g. "Underclocked 412Mhz".
How can I do this?
I can use HTML, PHP and Javascript.

You can do this using Ajax. The most easy way is making the AJAX request with jQuery.
Below an example:
Call a JavaScript function when the 'change' event ocurred on your combobox:
<select id="device" onchange="changeDevice(this.id);">[your options]</select>
Make an ajax request in your JavaScript method:
function changeDevice(deviceID){
$.ajax({
type:'post',
url:'[url of your php file]',
dataType:'text',
data:{device_id:deviceID},
success:function(response){
//assign the text response to your input text
$('#processor').val(response);
}
});}

You could fix this with plain old Javascript
<select name="combo">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="Duck">Duck</option>
<option value="Rabbit">Rabbit</option>
</select>
<input type="text" name="picked" id="picked">
<script>
document.getElementsByName('combo').item(0).onchange = function(){
document.getElementsByName('picked').item(0).value = document.getElementsByName('combo').item(0).value;
}
</script>

Related

How do I make the SELECT tag to change the URL

So i have this SELECT tags here
<select id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</select>
<button onclick="go()">GO</button>
Then a script here
<script>
function go() {
$.ajax({
url: 'url1.php?check=' + value,
type: 'GET',
async: true,
})
Now, I want to change the line of code that says: url: 'url1.php?check=' + value, to say whatever the selected option's id is rather than the hardcoded "ur1.php". How do I achieve these?
NOTE: I cut the code if you're wondering why is it like that.
Here's a working demo of what you need. I changed the following to make it work:
1) give your <option> tags value attributes (as per documentation) rather than ids. The one relating to the chosen option is then automatically read as being the value of the <select>.
2) get the currently selected URL value by using .val() to get the value of the <select>
3) (non-essential but good practice) using an unobtrusive event handler in the script itself rather than an inline "onclick".
4) (non-essential) you don't need async:true because that's already the default value.
var value = "something";
$("#go").click(function() {
var url = $("#url").val() + '.php?check=' + value;
console.log(url);
$.ajax({
url: url,
type: 'GET',
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="url">
<option value="url1">url 1</option>
<option value="url2">url 2</option>
</select>
<button type="button" id="go">GO</button>
The proper way to do this is to give each of your option's a value attribute. You can the get the select-element and get it's value (which will be the value of the selected option)
I added some code to help you:
function go() {
const select = document.getElementById('select');
const value = select.value; // <-- this here is the value you can use to make your request
console.log(value);
}
<select id="select">
<option value="url1">URL 1</option>
<option value="url2">URL 2</option>
</select>
<button onclick="go()">Go</button>
HTML Code:
<SELECT id="url">
<option id="url1" >url 1</option>
<option id="url2" >url 2</option>
</SELECT>
<button id = "button_go">GO</button>
Script:
$("#button_go").click(go);
function go() {
var value =$('#url').children("option:selected").attr('id');
alert("You have selected the ID- " + value);
// your ajax code
}
Check the jsfiddle working code : https://jsfiddle.net/1eq29w6a/4/

JavaScript - Pass selected drop down list value to method

This may be a simple thing, but I am trying to capture the selected value from a drop down list on an JSP page and use the selected value as an argument to a method. I am able to use the onchange event in the select tag to call a java script function and capture the value but I am not sure how to send the value to the method. I think there is a way to do this via an ajax based call but I am not sure how to accomplish this. Here is a sample of the test code I am using. Thank you.
function getSelected()
{
var selectedSource = document.getElementById("myselect").value;
console.log(selectedSource);
}
<select name="myselect" id="myselect" onchange="getSelected();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>
I edited the answer to include the post to the server using jQuery.
There are two errors in your javascript function:
First, you call getselected(), but the function name is getSelectedSource();
Second, you try to find sourceSystem, but your id is myselect.
Make a HTTP Post using jQuery and send a parameter myselect, for example, with value selectedSource.
In your servlet, you can get this parameter using request.getParameter("myselect")
<script src="http://code.jquery.com/jquery-1.5.js"></script>
<script>
function getSelected()
{
var selectedSource = $("#myselect").val();
console.log(selectedSource);
$.post("test", { myselect : selectedSource},
function(data) {
alert("Data Loaded: " + data);
});
}
</script>
<select name="myselect" id="myselect" onchange="getSelected();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
<option value="4">Four</option>
</select>

Add database default value to dropdown list using jQuery AJAX

I'm working with CRUD operation using jQuery AJAX and bootstrap modal in laravel. But the problem is when I want to edit something. I can't populate my dropdown list after an AJAX success request. How can I set database default value in my edit modal Dropdown List?
My Code:
$(document).ready(function() {
$('.acedit').click(function() {
$('#form')[0].reset();
$('#modal_form').modal('show'); // show bootstrap modal
var id = $(this).data('id');
$.ajax({
url: "{{route('academic.edit')}}",
method: 'post',
data: {
id: id,
'_token': "{{csrf_token()}}"
},
success: function(data) {
//$('#mycontrolId').selectmenu('refresh').val(myvalue).attr("selected", "selected");
$('.degree').val(data.degree).attr('selected', true);
$('.divison').val(data.division);
$('.year').val(data.year);
console.log(data); //{id: 2, user_id: 5, degree: "ssc", division: "First", year: "2009", …}
}
});
});
});
My Controller Method:
public function acadedit(Request $request){
$id=$request->id;
$info=Academic::find($id);
return $info;
}
My edit modal Dropdown list:
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
There is no selected attribute on the <select> element, it's only for the <option>s. However, you don't really need it, because setting the value of the <select> element is enough to change the selection. But you need to match the value exactly with the proper letter casing, so all capital letters in your case.
Change this:
$('.degree').val(data.degree).attr('selected',true);
To:
$('.degree').val(data.degree.toUpperCase());
If you really prefer to do it with the attribute on the <option> instead of the value of the <select>, then you need to add the <option> to the jQuery selector like this:
$('.degree option[value=' + data.degree.toUpperCase() + ']').attr('selected', true);
Demo:
$('.degree option[value=SSC]').attr('selected', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control degree">
<option value="">-Select Degree-</option>
<option value="SSC">SSC</option>
<option value="HSC">HSC</option>
<option value="BBA">BBA</option>
<option value="MBA">MBA</option>
</select>
If you want to use response data from your Controller by Ajax, then it better to return it in Json format:
Use return response()->json($info); instead of return $info;
As I can see from your console.log output you receive degree: "ssc", whereas
your select option is SSC, so you need to uppercase the data before use it: $('.degree').val(data.degree.toUpperCase()); or to downcase values of select options: <option value="ss">SSC</option>.

ASP.NET MVC4 with Razor - Filtering dropdownlist by value selected from another dropdownlist

I have to filter the options of a dropdownlist by value selected from another dropdown. In my database I have a table with all countries and a table with all cities of the world with a FK to the respective country.
Here is a part of my view and my page:
And my controller methods (the GET method of the page, the loading of all countries and the loading of all cities of a country): (I removed the image)
I have to handle the "onchange" event of the first dropdownlist to modify all the options of the second (calling the LoadCities method in my controller and passing the value of the selected item of first drop) but I have no idea about how to do it.
Thank you for your help!!
UDPADE
Thank #Shyju for your advices but it still does not working. I am a student and I don't know much about the topic, here are the results:
You can see that the Content-Length is 0, in fact the response panel is empty.
Why the type is xml? What is "X-Requested-With"? How can I fix it?
Use the onchange method (client side) of the first select and fill up seconds' options with an AJAX call.
You can listen to the change event on the first dropdown(Country), read the value of the selected option and make an ajax call to your server to get the cities for that country.
$(function(){
$("#Country").change(function(){
var countryId = $(this).val();
var url = "#Url.Action("LoadCities,"Country")"+countryId;
$.getJSON(url,function(data){
var options="";
$.each(data,function(a,b){
options+="<option value='"+ b.Value +"'>" + b.Text + "</option>";
});
$("#City").html(options);
});
});
});
Now your LoadCities should return the list of citites as Json.
public ActionResult GetCities(int id)
{
// I am hard coding a bunch of cities for demo.
// You may replace with your code which reads from your db table.
var dummyCities = new List<SelectListItem>
{
new SelectListItem { Value="1", Text="Detroit"},
new SelectListItem { Value="2", Text="Ann Arbor"},
new SelectListItem { Value="3", Text="Austin"}
};
return Json(dummyCities,JsonRequestBehaviour.AllowGet);
}
use javascript or jquery OnChange method.
and pass the 1st dropdown Id and use ajax to call the method by passing dropdown Id.
<div class="ui-widget">
<select id="pick">
<option value="">Select one...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="drop">
<option value="">Select one...</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
<option value="14">14</option>
</select>
</div>
$("#drop").change(function () {
var end = this.value;
var firstDropVal = $('#pick').val();
});

Post URL from multiple <select> elements

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.
Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.
1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Categories