HTML Select Menu - modify Javascript variable on change - javascript

I have a Javascript that stores a variable for a default phone number, but I would like users to be able to override this based on the options in a select menu. If they make a selection from the menu I would like the Javascript variable to be updated with the new value from the selected option.
Here's the script:
$("#callContact1").click(function() {
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber=0412345678&type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
I would like to edit the value of the 'recipientNumber=0412345678' in the url of the AJAX request function whenever this select menu is changed:
<select class="form-control" name="callBackNumber" id="callBackNumber">
<option value=""></option>
<option value="0418468103" selected>Mobile (0412345678)</option>
<option value="0294846565">Work (0299887766)</option>
<option value="0233445566">Home (0233445566)</option>
</select>
I'm not sure if this is possible or if there is a better way to construct this to achieve the same result?

Create a global variable with your defaultPhoneNumber.
var defaultPhoneNumber = $("#callBackNumber").val();
Update that variable on change of dropdownlist.
$("#callBackNumber").change(function(){
defaultPhoneNumber = $(this).val();
});
And use updated value in URL
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber="+ defaultPhoneNumber +"&type=makecall",
data: {},
type: "GET"
});

Use $("#callBackNumber").on("change", function() { and pass the this.value number
$("#callBackNumber").on("change", function() {
var number = this.value;
if(!number) {
return console.log("Please select a number!"); //
}
// Now let's use that number
$.ajax({
url: "https://www.server.com/callback.php?recipientNumber="+ number +"&type=makecall",
data: {},
type: "GET"
})
.then(function(data) {
$('#ajaxResponse').html(data).show();
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var ajaxError = 'There was an requesting the call back. HTTP Status: ' + httpStatus;
console.log('ajaxError: ' + ajaxError);
//make alert visible
$('#ajaxResponse').html(ajaxError).show();
})
})
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="callBackNumber" id="callBackNumber">
<option value=""></option>
<option value="0418468103" selected>Mobile (0412345678)</option>
<option value="0294846565">Work (0299887766)</option>
<option value="0233445566">Home (0233445566)</option>
</select>

Sure it is possible, and You have done something similar ;)
select element support's change event, which fires after selecting option from dropdown.
$('#callBackNumber').on('change', (event) => {
const value = event.target.value
fireCallback(value)
})
ofc You have to write fireCallback function, which will do the thing

This is how I would do it:
var phoneNum = "0412345678";
$("#callBackNumber").change(function() {
phoneNum = $(this).val();
});
Here is the JSFiddle demo
Create a global variable, always concatenate it in the ajax URL. Update the value of the variable whenever the dropdown is changed. You will always have latest value in your variable and hence in your ajax URL.

Related

Selected option (HTML dropdown list) isn't saved to the localStorage

I'm trying to save the "selected" option from the <select> HTML tag to the localStorage, so when I refresh the page the last selected option is selected. I can see that it's saved in the console.log, but it's not working on the page load. How can I make it work?
<select class="multiply_ing">
<option value="0.5">0.5x</option>
<option value="1" selected>1x</option>
<option value="1.5">1.5x</option>
<option value="2">2x</option>
<option value="2.5">2.5x</option>
<option value="3">3x</option>
<option value="4">4x</option>
<option value="5">5x</option>
<option value="6">6x</option>
<option value="8">8x</option>
<option value="10">10x</option>
</select>
<p class="portion" data-val="<?php echo $portion; ?>"></p> <!-- PHP Generated value, let's just say it's "1" -->
<div class="ingredient">
<p data-val="1"></p>
<p data-val="5"></p>
<p data-val="6"></p>
</div>
<script>
$(function() {
$(".multiply_ing").on("change", function() {
let multiply_val =+ this.value;
$('.ingredient p:nth-child(1)').each(function() {
let ing =+ this.dataset.val;
this.innerHTML = ing * multiply_val;
});
$('.multiply_ing option').each(function() {
let multi_opt = $(this).val();
let portion = parseFloat(document.querySelector(".portion").dataset.val);
let portions = multi_opt * portion;
});
let portion =+ document.querySelector(".portion").dataset.val;
document.querySelector(".portion").innerHTML = portion * multiply_val;
}).change();
jQuery($ => {
let $select = $('.multiply_ing');
// get on load
$select.val(localStorage.getItem('value') || 1); // 1 = default value
$select.on('change', e => {
localStorage.setItem('value', e.target.value);
});
});
});
</script>
Note: there is more code than in this example, but it's irrelevant to the problem.
To do what you require you can just use val() to both get and set the value of the select when required:
jQuery($ => {
let $select = $('.multiply_ing');
// get on load
$select.val(localStorage.getItem('value') || 1); // 1 = default value
$select.on('change', e => {
localStorage.setItem('value', e.target.value);
});
});
Also note that the each() in your example is doing nothing and can be removed. In addition, multiply_val is not defined anywhere.
As a general rule, if you're going to incur the performance penalty of loading jQuery in to the DOM, then you're better off making use of it everywhere. Mixing JS and jQuery just leads to confusion.
To store value in localStorage you have to use key value pair like this localStorage.setItem('selectedValue',yourValue) and to get value use key to access the saved value localStorage.getItem('selectedValue')
$(function() {
$('.multiply_ing').change(function() {
localStorage.setItem('selectedValue', this.value);
});
if(localStorage.getItem('todoData')){
$('.multiply_ing').val(localStorage.getItem('selectedValue'));
}
});
for working code you can see this demo

posting to database via ajax

I have a js function to update the database according to values from the select input fields.
This is the javascript function:
function getStatusAction()
{
var matchId = $(this).attr('match-id');
var status = jQuery('#match-status').val();
jQuery.ajax({
url:'../core/match_stat.php',
type:'POST',
data:{matchId:matchId,status:status},
success: function(data){
//alert("Ok");
},
error: function(){
alert("Error..");
},
});
}
jQuery('select[name="match-status"]').change(getStatusAction);
Part of the html:
<tr>
<td>
<select class="input" name="match-status" match-id="<?=$ActiveMatch['id'];?>" id="match-status">
<option value="3" <?= (($ActiveMatch['status'] == '3')?'selected':'')?>> </option>
<option value="1" <?= (($ActiveMatch['status'] == '1')?'selected':'');?> >won</option>
<option value="2" <?= (($ActiveMatch['status'] == '2')?'selected':'');?> >lost</option>
</select>
</td>
</tr>
The function is supposed to get the id of the match eg 1,2... and the status eg 1,2,3 for loose, win and default status respectively.
The problem is I can only update the first row of data. If I try doing so on another row of data, the values from the first call are used. For example if I update first row status to win, if I try updating second row to loose it is updated to win. The status of the previous operation.
How can I solve this?
you can try
function getStatusAction(Element) //<< add parameter here
{
var matchId = $(Element).attr('match-id'); // <<< use it here
var status = jQuery('#match-status').val();
jQuery.ajax({
url:'../core/match_stat.php',
type:'POST',
data:{matchId:matchId,status:status},
success: function(data){
//alert("Ok");
},
error: function(){
alert("Error..");
},
});
}
jQuery('select[name="match-status"]').on('change' , function(){
getStatusAction(this); // << use the function here
});
Note: id should be unique so if you have only one element with id match-status its fine .. but if your selects have the same id you need to change id="match-status" to class="match-status" and change var status = jQuery('#match-status').val(); to var status = $(Element).val();

I am new to node js how to get dependent dynamic dropdown from database

my node code:
app.get('/block_name', function (req,res){
var sql='SELECT `block_name`,`block_id` FROM `tbl_block` ';
connection.query(sql,function(err, result) {
if (err) throw err;
res.json(result);
});
});
app.get('/site_name', function (req,res){
var sql='SELECT `site_name`,`site_id` FROM `tbl_site` ';
connection.query(sql,function(err, result) {
if (err) throw err;
res.json(result);
});
});
HTML
Site
<select name="site" id="dropdown" >
<option value="">- select -</option>
</select>
<label class="field" >Block</label>
<select name="block" id="dropdown1" >
<option value="">- select -</option>
</select>
SCRIPT
<script>
$(document).ready(function(){
$.ajax({
url : "/site_name",
type : "GET",
success : function(data){
var len = data.length;
console.log(data);
$("#dropdown").empty();
for(var i =0; i<len;i++){
var value1 = data[i]['site_name'];
var value2 = data[i]['site_id'];
$("#dropdown").append("<option value='"+value2+"' >"+value1+"</option>");
}
}
});
});
$(document).ready(function(){
$.ajax({
url : "/block_name",
type : "GET",
success : function(data){
var len = data.length;
console.log(data);
$("#dropdown1").empty();
for(var i =0; i<len;i++){
var value1 = data[i]['block_name'];
var value2 = data[i]['block_id'];
$("#dropdown1").append("<option value='"+value2+"' >"+value1+"</option>");
}
}
});
});
</script>
my second dropdown lists all the data but i need particular thing to be listed according to the first dropdown.
Thanks in advance..
Sorry for my bad English
Anytime the first drop-down changes value, you need to repopulate the second drop-down based on the select value in the first drop-down - usually by rerunning your ajax call to load the second drop-down, but using the value of the first drop-down to decide which data to request from the server.
You would do this by installing an event handler on the first drop-down so you can detect any time its value is changed and then you would repopulate the second dropdown with a fresh ajax call whenever that event on the first drop-down occurs.

Get previous value of dropdown after onchange event jQuery

How do I get the previous value of my AUTO-Generated dropdown menu after an onchange event? Example
<select class="form-control" name="Diabetes_UK_3147" id="Diabetes_UK_3147" onchange="return verifyUpdateResponseGross(this);">
<option value="Yes">Yes</option>
<option value="Possibly">Possibly</option>
<option value="">N/A</option>
</select>
and I have this function
function verifyUpdateResponseGross(val)
{
var updated_response = val.value;
var colheader = val.name
var before_gross = $('#new_gross').val();
$.ajax({
url: "qa/api/crm/getquestion",
type: 'GET',
data: {'colheader':colheader},
success: function(result){
// var costperlead = result;
// if(updated_response != "")
// {
// var new_gross_amount = parseFloat(before_gross) + parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// else
// {
// var new_gross_amount = parseFloat(before_gross) - parseFloat(costperlead);
// $('#new_gross').val(new_gross_amount);
// }
// console.log(costperlead);
}});
}
The reason I want to get the previous value is I need a checking that if the dropdown value is empty (N/A) then I need to perform some operation and if the value is not empty then I need perform another operation, But when the value gis not empty but the same from the previous value, then do nothing.
Those operation are those in comments. Thanks
UPDATE The id and name is autogenerated. That's why I have a
onchange="return verifyUpdateResponseGross(this);"
This will handle the change and do necessary operation.
This is it is autogenerated
Best way to do it by jquery :
$(document).ready(function(){
var previous;
$("#Diabetes_UK_3147").on("focus click",function () {
previous = this.value; // Old vaue
}).change(function() {
var value = this.value; // New Value
$('span').text('Old Value : '+previous+' New Value : '+value)
});
})
here the fiddle http://jsfiddle.net/Laa2hL3b/
Edited : in auto-Generated dropdown you can add a custom class for example "myselectbox"
<select class="form-control myselectbox"
and make change here
$(".myselectbox").on(/* other code remain same */
Use data to store the data instead a global variable:
$("#Diabetes_UK_3147").on("focus",function(){
$(this).data('previous',$(this).val());
}
Then you can access previous value by $("#Diabetes_UK_3147").data('previous');
jQuery data
Use data-* as below. Also, remove the inline event handler onchange="return verifyUpdateResponseGross(this);" and do it the unobtrusive way.
var $select = $("#Diabetes_UK_3147");
$select.data("previous-val", $select.val());
$select.on("change", function() {
var current_value = $(this).val();
if (current_value == "") {
//Do stuff when empty
} else if ( current_value != $(this).data("previousVal") && current_value != "" ) {
//Do stuff when not empty and current value != previous value
}
});
var $select = $("#my-select");
$select.data("prevVal", $select.val()).data("currVal", $select.val()).on("change", function () {
var $this = $(this);
$this.data("prevVal", $this.data("currVal")).data("currVal", $this.val());
// do your staff here. Previous value is available in $this.data("prevVal")
});

Simualating user clicks using JavaScript or JQuery

There is a website that I want to simulate user clicks on. In this website, there is the following div, let's call it div1, where there is a dropdown menu. There are actually other two similar divs (lets call them div2 and div3) following but I didn't place here for the simplicity. When you select one of the item in the dropdown menu in div1, the div2 is enabled (disabled by default in the beginning) and its menu content is fetched from database based on the item selected from the div1.
I can select the menu item using following script.
Code:
function setSelectedValue(selectObj, valueToSet) {
for (var i = 0; i < selectObj.options.length; i++) {
if (selectObj.options[i].value== valueToSet) {
selectObj.options[i].selected = true;
return;
}
}
}
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
However, when I do this, the div2 is never enabled. I tried jQuery code to emit change signal on the dropdown menu but it doesn't work. When I was debugging the below html code, I saw the button tag there and I immediately thought that it submits when there is click. However, I don't see any form. If I debug the website using chrome, I see that the code jumps different js files when I select an item in the menu. Could anyone guide me how I can find out which signal is triggered when an item is selected? Apparently they do some tricks in the website to prevent normal ways of clicking
Code:
<div data-custom-select="" class="custom-select focus">
<label for="level1-option" class="has-hidden-label label-text">Sections</label>
<span class="btn-select icon-down_thin">Choose a section</span>
<select class="categories-options" data-level="1" name="level1-option" id="level1-option" required="">
<option value="">Choose a section</option>
<option value="p1" data-href="/callback/discovery/p1/">P1</option>
<option value="p2" data-href="/callback/discovery/p2/">P2</option>
<option value="p3" data-href="/callback/discovery/p3/">P3</option>
<option value="p4" data-href="/callback/discovery/p4/">P4</option>
</select>
<span class="icon-down_thin"></span>
<button type="submit" class="category-submit ui-button-secondary ">Choose</button>
Usually you could use:
$("#level1-option").val(valueToSet).trigger("click")
or
$("#level1-option").val(valueToSet).trigger("change")
but it might depend on the rest of the code on the webpage.
Try ...
$(element).trigger('click');
... from jQuery.
Try dispatching onchange event once you have changed its value:
var number = document.getElementById('level1-option');
setSelectedValue(number, "p3");
var evt = document.createEvent("HTMLEvents");
evt.initEvent("change", false, true);
number.dispatchEvent(evt);
Sorry, that I couldn't help with the overlay issue. Your markup is pretty complex.
Anyway, I coded a bit for the updating/fetching data from database. Please find below a demo of it.
The demo is also here at jsFiddle
The JSON data looks like this {"data": ["1st_1", "1st_2", "1st_3"]}
During my work I had one issue that wasn't that easy to solve, but another SO question helped here. If you'd only use the change event you can't trigger the first element to fetch your next data.
The counter trick works pretty well.
var dynamicOptions = (function () {
var url; // here you can add your url to the backend script
// urlList only required for demo because no backend available
var urlList = ['http://www.mocky.io/v2/54839e2a2f4b84a0041bba49',
'http://www.mocky.io/v2/54839e4c2f4b84a5041bba4a',
'http://www.mocky.io/v2/54839e6a2f4b84a9041bba4b'];
var cc = 0; // click counter
// e.g. $optionEl = $('#firstSelection');
// $nextOptionEl = $('#secondSelection');
function Selector($optionEl, $nextOptionEl) {
this.$optionEl = $optionEl;
this.$nextOptionEl = $nextOptionEl;
this.ajaxRequest = function (optionValue) {
return $.ajax({
type: 'GET', // later 'POST'
//data: {'data': optionValue}, // for posting
url: url,
contentType: "application/json",
dataType: 'jsonp',
context: this,
});
};
this.getData = function(value) {
url = urlList[value]; // simulating backend returns based on this value
var ajaxReq = this.ajaxRequest(value); // this.value not used in this demo
ajaxReq.success(this.jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
};
// handle click and change event. Source from here: https://stackoverflow.com/questions/11002421/jquery-event-to-fire-when-a-drop-down-is-selected-but-the-value-is-not-change
this.clickHandler = function ($element) {
//console.log($element);
var that = this;
return $element.click(function () {
//console.log('clicked');
cc++;
if (cc == 2) {
$(this).change();
cc = 0;
}
}).change(function (e) {
cc = -1; // change triggered
//console.log(this.value);
that.getData(this.value);
});
}
this.clickHandler($optionEl);
this.jsonCallback = function (json) {
var $nextEl = this.$nextOptionEl;
$nextEl.empty(); // clear selection
$nextEl.prop('disabled', false); // enable 2nd select
this.triggerChangeEvent(); // maybe a check if they really changed would be good
$.each(json.data, function (index, value) {
$('<option/>')
.val(index)
.text(value)
.appendTo($nextEl);
});
};
this.triggerChangeEvent = function () {
var event = jQuery.Event("optionsChanged");
event.context = this;
event.message = "Options changed, update other depending options";
event.time = new Date();
$.event.trigger(event);
};
}
return {
Selector: Selector
}; // make Selector public
})();
$(function () {
var $first = $('#firstSelection');
var $second = $('#secondSelection');
var $third = $('#thirdSelection');
// use our dynamic options selector class
var options12 = new dynamicOptions.Selector($first, $second);
var options23 = new dynamicOptions.Selector($second, $third);
$(document).on('optionsChanged', function (e) {
console.log("options changed", e);
var obj_id = e.context.id;
//console.log(obj_id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div>
<form role="form">
<div class="form-group">
<label>Please select first value:</label>
<select id="firstSelection" class="form-control">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
</div>
<div class="form-group">
<label>Please select second value:</label>
<select id="secondSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
<div class="form-group">
<label>Please select third value:</label>
<select id="thirdSelection" class="form-control" disabled="true">
<!-- fetched from server -->
</select>
</div>
</form>
</div>

Categories

Resources