Calling javascript function from html drop down automatically - javascript

I am not good in html or JavaScript and I have been trying alot to automatically call the JavaScript function from html drop down.
My requirement is to hide the html drop down and hard code the value of drop down and automatically call the function which will query the database on the basis of this hard coded value. Those other retrieved values from db will be used in UI.
JavaScript function is :
Behaviour.register({
'#retailerSelect': function(select) {
select.onchange = function() {
if (getValue(select) == ""){
setValue('query(branch)', "");
setValue('query(store)', "");
setValue('query(terminalId)', "");
}
this.form.submit();
}
},
HTML drop down is :
<td width="33%" align="center" >
<payo:layout columns="1">
<payo:cell nowrap="nowrap" align="center">
<html:select styleId="retailerSelect" style="margin:2px" property="query(retailer)">
<html:option value="1"><bean:message key="tms.dropdown.select.retailer"/></html:option>
<c:forEach var="retailer" items="${retailers}">
<html:option value="${retailer.id}">${retailer.retailerName}</html:option>
</c:forEach>
</html:select>
</payo:cell>
</payo:layout>
</td>
I need the value of drop down as 1, which will automatically call this onchange function to query the db.
please help,thanks in advance.

Use onchange to call the function
function selectedNum(number) {
alert(number);
}
<select name="numbers" onchange="selectedNum(this.value)">
<option value="">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>

This can be achieved by two ways:
1. <select id="mySelect"></select>
$('#mySelect').click(function(){
var value = $(this).val();
// ajax call
});
2. <select onChange="myFunction(this.value)"></select>
function myFunction(value)
{
// ajax call
}

Related

I have an onChange function with this parameters that works fine but I also want to apply the function onLoad

I have an onchange function that when pending is selected, it will add a value in the input field, but I also want this to apply onload, currently, pending is already selected, so when the page loads, i want to add a value to the input field.
function validateForm1(k, x) {
if (x.value == "pending") {
document.getElementById(k).value = "populate";
}
}
<input type="text" value="" id="target1">
<select data-uid="target1" onchange="validateForm1(this.getAttribute('data-uid'),this)">
<option></option>
<option selected value="pending">pending</option>
<option value="testing">testing</option>
</select>
Call your validate function and to populate the variables you can find them with javascript functions like getElementsByName. That's the easiest way with the code you have, but, to improve on it, I would suggest adding an id to your select and then using getElementById to get the element.
Here's a working solution:
function validateForm1(k, x) {
if (x.value == "pending") {
document.getElementById(k).value = "populate";
}
}
validateForm1(document.getElementsByTagName("select")[0].getAttribute('data-uid'), document.getElementsByTagName("select")[0]);
<input type="text" value="" id="target1">
<select data-uid="target1" onchange="validateForm1(this.getAttribute('data-uid'),this)">
<option></option>
<option selected value="pending">pending</option>
<option value="testing">testing</option>
</select>

display and value depending options of drop down menus with different values

I want to submit my selected value in the dropdown menu to my database, but the value that is added to the database is not the same as what I chose.
This is the record that was inserted, and the "kuarter" field value is "kuching-01":
But these are the selections I chose, where the field "kuarter" is "JALAN DURIAN BURONG STAMPIN":
How do I add the value "JALAN DURIAN BURONG STAMPIN" to the database instead of "kuching-01"?
This is my javascript:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var $options = $("#kuarter").clone(); // this will save all initial options in the second dropdown
$("#kawasan").change(function() {
var filters = [];
if ($(this).val() == "") {
$(this).find("option").each(function(index, option) {
if ($(option).val() != "")
filters.push($(option).val());
});
} else {
filters.push($(this).val())
}
$("#kuarter").html("");
$.each(filters, function(index, value) {
$options.find("option").each(function(optionIndex, option) { // a second loop that check if the option value starts with the filter value
if ($(option).val().startsWith(value))
$(option).clone().appendTo($("#kuarter"));
});
});
});
});
</script>
This is the HTML code for the dropdowns:
<tr valign="baseline">
<td nowrap="nowrap" align="right">Kawasan:</td>
<td><select name="pilih_kawasan" id="kawasan">
<option value="none">SILA PILIH</option>
<option value="kuching">KUCHING</option>
<option value="lundu">LUNDU</option>
<option value="sriaman">SRI AMAN</option>
<option value="betong">BETONG</option>
</select></td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Kuarter:</td>
<td><select name="pilih_kuarter" id="kuarter">
<option value="none-01"></option>
<option value="kuching-01">JALAN DURIAN BURONG STAMPIN</option>
<option value="lundu-01">JALAN SEKETI</option>
<option value="sriaman-01">JALAN FOO CHOW</option>
<option value="sriaman-02">JALAN SABU</option>
<option value="betong-01">JALAN TANJUNG ASSAM</option>
</select></td>
</tr>
The reason is that you are saving the value of the selected option in #kuarter, and not the text that's displayed in the e.g. the value for the option you are selecting is kuching-01:
<option value="kuching-01">JALAN DURIAN BURONG STAMPIN</option>
As other code depends on the value, you can't change the option value to match the text you want.
What we can do instead is save the text in a hidden input that will get submitted with the form. For this to work, the input has to have the same name as the option currently has, so that your processing code will recognise it.
To do this we need to:
Change the name of the select so that our new hidden input can use the name pilih_kawasan and sumbit the value for processing, e.g. <select name="pilih_kawasan_select" id="kawasan">
Add a hidden input to your form with the name pilih_kawasan to store the text, e.g.: <input type="hidden" name="pilih_kawasan" id="pilih_kawasan_value" value="">
Add javascript function to update the value of the hidden field #pilih_kawasan_value with the selected text (i.e. not value).
Call this function every time the #kuarter dropdown changes. This needs to be done in 2 places: when a new value is selected in #kuarter, and also when the value of 'kawasan' changes (because that changes the values in #kuarter).
Working snippet
The HTML & jQuery below are working here, run the snippet to see what its doing.
$(document).ready(function() {
var $options = $("#kuarter").clone();
$("#kawasan").change(function() {
var filters = [];
if ($(this).val() == "") {
$(this).find("option").each(function(index, option) {
if ($(option).val() != "")
filters.push($(option).val());
});
} else {
filters.push($(this).val())
}
$("#kuarter").html("");
$.each(filters, function(index, value) {
$options.find("option").each(function(optionIndex, option) {
if ($(option).val().startsWith(value)) {
$(option).clone().appendTo($("#kuarter"));
// (4.) ADDED: the #kuarter values have changed, so update the hidden input to the selected text
selected_text = $("#kuarter option:selected").text(); // get the text from the selected option
setKuarterValue(selected_text); // call our function to update the hidden input
}
});
});
});
// (4.) ADDED: Update the hidden input any time the #kuarter dropdown is changed
$("#kuarter").change(function() {
// get the text from the selected option in #kawasan
selected_text = $("#kuarter option:selected").text();
setKuarterValue(selected_text); // call our function to update the hidden input
});
});
/* (3.) function to set the values of the hidden input "#pilih_kuarter"
that will be submitted to your processing code. */
function setKuarterValue(myval) {
// if the value hasn't changed , no need to update
if ($("#pilih_kuarter").val() == myval) return;
// set the value of the hidden input with the selected text
$("#pilih_kuarter").val(myval);
// just for testing, so we can see the value that will be submitted - delete when its working for you
console.log ("Set pilih_kuarter value = "+ myval);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Kawasan:</td>
<td>
<!-- (1.) UPDATED: Change the name of the select, as we're going to submit our hidden input using this name instead -->
<select name="pilih_kawasan" id="kawasan">
<option value="none">SILA PILIH</option>
<option value="kuching">KUCHING</option>
<option value="lundu">LUNDU</option>
<option value="sriaman">SRI AMAN</option>
<option value="betong">BETONG</option>
</select>
</td>
</tr>
<tr valign="baseline">
<td nowrap="nowrap" align="right">Kuarter:</td>
<td>
<select name="pilih_kuarter_select" id="kuarter">
<option value="none-01"></option>
<option value="kuching-01">JALAN DURIAN BURONG STAMPIN</option>
<option value="lundu-01">JALAN SEKETI</option>
<option value="sriaman-01">JALAN FOO CHOW</option>
<option value="sriaman-02">JALAN SABU</option>
<option value="betong-01">JALAN TANJUNG ASSAM</option>
</select>
</td>
</tr>
<!-- (2.) ADDED: add a new hidden input to store the required text
this must have the name=pilih_kuarter so it will submit the value to you database -->
<input type="hidden" name="pilih_kuarter" id="pilih_kuarter" value="">
</table>
This is the result..the value in kuarter's should be in kawasan's value and the kawasan's value should in kuarter's value

javascript enable and disable a combobox

I am a beginner in java-script , what I am doing right here is trying to make my combo-box named "dale" to enable and disable when i select "Reasons Specific Categorized" from my combo-box named "repSelect" but i keep getting an error on my java-script.
function makeEnable(value){
if(value=="rep4"){
var x=document.getElementById("dale")
x.disabled=false
}else{
var x=document.getElementById("dale")
x.disabled=true
}
}
</script>
</script>
<select onChange="makeEnable(value)" name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte" >
</form>
My modification But dosent work
function makeEnable(){
var e = document.getElementById("repSelect");
var strUser = e.options[e.selectedIndex].value;
if(strUser=="rep4"){
document.getElementById("dale").disabled=false;
}else{
document.getElementById("dale").disabled=true;
}
}
You are using the .getElementById() method, but your element doesn't have an id defined. Add an id in the html:
<select id="dale" name="dale">
You may also need to modify the call to your function in the first select's onchange handler, to pass this.value instead of just value:
<select onChange="makeEnable(this.value)" name="repSelect">
You can also substantially simplify your function as follows:
function makeEnable(value){
document.getElementById("dale").disabled = value!="rep4";
}
Demo: http://jsfiddle.net/3t16p5p9/
EDIT: I just noticed that you had the jquery tag on your question. To use jQuery, remove the inline onChange= attribute and then add this to your script:
$(document).ready(function() {
$("select[name=repSelect]").change(function() {
$("#dale").prop("disabled", this.value!="rep4");
}).change();
});
This binds a change handler to the first select, and then calls it immediately so that the second one will be appropriately enabled or disabled when the page loads (as requested in a comment).
Demo: http://jsfiddle.net/3t16p5p9/2/
Actually you are using document.getElementById but your combobox doesn't have an Id.
Thats the reason its not working.
Instead of adding onchange in the html, use as below:
<select id='repselect' onchange=makeEnable() name="repSelect">
<option value="rep1">Employee</option>
<option value="rep2">Category Reasons Overall </option>
<option value="rep3">Department Overall </option>
<option value="rep4">Reasons Specific Categorized </option>
</select>
<select id="seldale" name="dale">
<option value="rep1">dale</option>
</select>
<input class="button" type="submit" value="Generar Reporte"/>
$('#repselect').change(function(){
if(this.value=="rep4"){
var x= document.getElementById("seldale")
x.disabled=false
}else{
var x =document.getElementById("seldale")
x.disabled=true
}
});

DropDown menu that when chosen turns option into a button

does anyone know if there is a way to make a dropdown menu that when an option is chosen it then turns that option into a button using html or is that only possible in php or is it not possible at all
You will have to learn javascript to be able to do that, there is an event fired called onselect, when you bind to that event with javascript using addEventListener you will be able to read the .value of the <select> field and then create a button using the createElement method.
Try this with jQuery
<script>
$(document).ready(function(){
var sel_html = $('#element_place').html();
$('#select_button').change(function(){
var sel_option = $('#select_button').val();
$('#select_button').remove();
new_ele = $('<input>').attr('type','button').attr('value',sel_option);
$('#element_place').append(new_ele);
});
});
</script>
<div id="element_place">
<select id="select_button">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
</div>
You can use this its working
Html
<input type="button" id="conv_but" value="" style="display:none">
<select name="data_select" id="data_select" onchange="converttobutton(this.value);">
<option value="One">One</option>
<option value="Two">Two</option>
<option value="Three">Three</option>
<option value="Four">Four</option>
<option value="Five">Five</option>
<option value="Six">Six</option>
</select>
Javascript
<script type="text/javascript">
function converttobutton(selected)
{
document.getElementById('conv_but').value = selected;
document.getElementById('data_select').style.display = 'none';
document.getElementById('conv_but').style.display = '';
}
</script>
I think you need change() event handler . Create a function inside the change() event for creating the button
$("ID of the dropdownbox").change (function () {
//code for creating button(this.value) give the selected option
var $something= $('<input/>').attr({ type: 'button',
name:'btn1', value:this.value});
//append this variable inside a div having ID `button_div`
$("#button_div").append($something);
});

How to pass parameters on onChange of html select

I am a novice at JavaScript and jQuery. I want to show one combobox-A, which is an HTML <select> with its selected id and contents at the other place on onChange().
How can I pass the complete combobox with its select id, and how can I pass other parameters on fire of the onChange event?
function getComboA(selectObject) {
var value = selectObject.value;
console.log(value);
}
<select id="comboA" onchange="getComboA(this)">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
The above example gets you the selected value of combo box on OnChange event.
Another approach wich can be handy in some situations, is passing the value of the selected <option /> directly to the function like this:
function myFunction(chosen) {
console.log(chosen);
}
<select onChange="myFunction(this.options[this.selectedIndex].value)">
<option value="1">Text 1</option>
<option value="2">Text 2</option>
</select>
For how to do it in jQuery:
<select id="yourid">
<option value="Value 1">Text 1</option>
<option value="Value 2">Text 2</option>
</select>
<script src="jquery.js"></script>
<script>
$('#yourid').change(function() {
alert('The option with value ' + $(this).val() + ' and text ' + $(this).text() + ' was selected.');
});
</script>
You should also know that Javascript and jQuery are not identical. jQuery is valid JavaScript code, but not all JavaScript is jQuery. You should look up the differences and make sure you are using the appropriate one.
JavaScript Solution
<select id="comboA">
<option value="">Select combo</option>
<option value="Value1">Text1</option>
<option value="Value2">Text2</option>
<option value="Value3">Text3</option>
</select>
<script>
document.getElementById("comboA").onchange = function(){
var value = document.getElementById("comboA").value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = function(evt){
var value = evt.target.value;
};
</script>
or
<script>
document.getElementById("comboA").onchange = handleChange;
function handleChange(evt){
var value = evt.target.value;
};
</script>
I found #Piyush's answer helpful, and just to add to it, if you programatically create a select, then there is an important way to get this behavior that may not be obvious. Let's say you have a function and you create a new select:
var changeitem = function (sel) {
console.log(sel.selectedIndex);
}
var newSelect = document.createElement('select');
newSelect.id = 'newselect';
The normal behavior may be to say
newSelect.onchange = changeitem;
But this does not really allow you to specify that argument passed in, so instead you may do this:
newSelect.setAttribute('onchange', 'changeitem(this)');
And you are able to set the parameter. If you do it the first way, then the argument you'll get to your onchange function will be browser dependent. The second way seems to work cross-browser just fine.
jQuery solution
How do I get the text value of a selected option
Select elements typically have two values that you want to access.
First there's the value to be sent to the server, which is easy:
$( "#myselect" ).val();
// => 1
The second is the text value of the select.
For example, using the following select box:
<select id="myselect">
<option value="1">Mr</option>
<option value="2">Mrs</option>
<option value="3">Ms</option>
<option value="4">Dr</option>
<option value="5">Prof</option>
</select>
If you wanted to get the string "Mr" if the first option was selected (instead of just "1") you would do that in the following way:
$( "#myselect option:selected" ).text();
// => "Mr"
See also
.val() jQuery API Documentation
This is helped for me.
For select:
$('select_tags').on('change', function() {
alert( $(this).find(":selected").val() );
});
For radio/checkbox:
$('radio_tags').on('change', function() {
alert( $(this).find(":checked").val() );
});
You can try bellow code
<select onchange="myfunction($(this).val())" id="myId">
</select>
Html template:
<select class="staff-select">
<option value="">All</option>
<option value="196">Ivan</option>
<option value="195">Jon</option>
</select>
Js code:
const $staffSelect = document.querySelector('.staff-select')
$staffSelect.onchange = function () {
console.log(this.value)
}
Just in case someone is looking for a React solution without having to download addition dependancies you could write:
<select onChange={this.changed(this)}>
<option value="Apple">Apple</option>
<option value="Android">Android</option>
</select>
changed(){
return e => {
console.log(e.target.value)
}
}
Make sure to bind the changed() function in the constructor like:
this.changed = this.changed.bind(this);
this code once i write for just explain onChange event of select you can save this code as html and see output it works.and easy to understand for you.
<html>
<head>
<title>Register</title>
</head>
<body>
<script>
function show(){
var option = document.getElementById("category").value;
if(option == "Student")
{
document.getElementById("enroll1").style.display="block";
}
if(option == "Parents")
{
document.getElementById("enroll1").style.display="none";
}
if(option == "Guardians")
{
document.getElementById("enroll1").style.display="none";
}
}
</script>
<form action="#" method="post">
<table>
<tr>
<td><label>Name </label></td>
<td><input type="text" id="name" size=20 maxlength=20 value=""></td>
</tr>
<tr style="display:block;" id="enroll1">
<td><label>Enrollment No. </label></td>
<td><input type="number" id="enroll" style="display:block;" size=20 maxlength=12 value=""></td>
</tr>
<tr>
<td><label>Email </label></td>
<td><input type="email" id="emailadd" size=20 maxlength=25 value=""></td>
</tr>
<tr>
<td><label>Mobile No. </label></td>
<td><input type="number" id="mobile" size=20 maxlength=10 value=""></td>
</tr>
<tr>
<td><label>Address</label></td>
<td><textarea rows="2" cols="20"></textarea></td>
</tr>
<tr >
<td><label>Category</label></td>
<td><select id="category" onchange="show()"> <!--onchange show methos is call-->
<option value="Student">Student</option>
<option value="Parents">Parents</option>
<option value="Guardians">Guardians</option>
</select>
</td>
</tr>
</table><br/>
<input type="submit" value="Sign Up">
</form>
</body>
</html>
function setMyValue(v) {
console.log(v);
}
<select onchange="setMyValue(this.value)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
This worked for me onchange = setLocation($(this).val())
Here.
#Html.DropDownList("Demo",
new SelectList(ViewBag.locs, "Value", "Text"),
new { Class = "ddlStyle", onchange = "setLocation($(this).val())" });
Simply:
function retrieve(){
alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve_other() {
alert(myForm.SMS_recipient.options[document.getElementById('SMS_recipient').selectedIndex].text);
}
function retrieve() { alert(document.getElementById('SMS_recipient').options[document.getElementById('SMS_recipient').selectedIndex].text);
}
<HTML>
<BODY>
<p>RETRIEVING TEXT IN OPTION OF SELECT </p>
<form name="myForm" action="">
<P>Select:
<select id="SMS_recipient">
<options value='+15121234567'>Andrew</option>
<options value='+15121234568'>Klaus</option>
</select>
</p>
<p>
<!-- Note: Despite the script engine complaining about it the code works!-->
<input type="button" onclick="retrieve()" value="Try it" />
<input type="button" onclick="retrieve_other()" value="Try Form" />
</p>
</form>
</HTML>
</BODY>
Output:
Klaus or Andrew depending on what the selectedIndex is. If you are after the value just replace .text with value. However if it is just the value you are after (not the text in the option) then use document.getElementById('SMS_recipient').value
//html code
<select onchange="get(this)">
<option value="a">1</option>
<option value="b">2</option>
<option value="c">3</option>
</select>
//javscript code
function get(select) {
let value = select.value;
console.log(value);
}

Categories