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();
Related
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.
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.
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>
My View code in MVC: I want to disable the Dropdownlist in View code when the checkbox is checked.
function SaveNewGroup() {
var group = RetrieveGroup();
var IsChecked = $(IsAssociation).is(":checked");
var url = (IsChecked) ? "/Administration/SaveNewGroupforIsAssociation" : "/Administration/SaveNewGroup";
var userID = $('#groupunderwriter').val();
$.ajax({
type: "POST",
url: url,
data: group,
datatype: "json",
success: function (groupID) {
if (groupID > 0) {
GetGroups();
$('#groupdialog').dialog('close');
}
else {
alert("Unable to create Group.");
}
}
});
}
Check box:
<tr>
<td>
<label>Is Association</label></td>
<td>
<input type ="checkbox" id="IsAssociation"/>
</td
>
and my dropdownlist:
<tr>
<td>Underwriter Name:</td>
<td>
<select id="groupunderwriter" style="width:150px;">
<option value ="0"></option>
#foreach (RMS.UserService.User u in Model.GroupUnderWriters)
{
<option value="#u.UserID">
#if(Model.MasterGroupAttribute.UserID == u.UserID)
{
#:selected="selected"
}
>#(u.FirstName + " " + u.LastName )</option>
}
</select>
</td>
</tr>
How to disable the dropdownlist when the checkbox is checked or enable it when not checked?
A short version would look like this:
$('#IsAssociation').change(function() {
$('#groupunderwriter').attr('disabled', $(this).is(':checked'));
});
Have a look at this fiddle. It works fine for me. i don't know why all the above are not working for you. I just used the jQuery ON event listener in case you have a race condition and these elements don't exist when you are creating a binding for them. Unlikely but hey, my example works. This isn't the ideal way to do it but it may give you some insight as to whatever is wrong with your code.
<input type ="checkbox" id="IsAssociation" /><span>your checkbox</span>
<br/>
<br/>
<select id="groupunderwriter" style="width:150px;">
<option value ="0">Hello</option>
<option value ="1">Goodbye</option>
</select>
$(document).on('change', '#IsAssociation', function(){
if($(this).prop('checked')){
$('#groupunderwriter').attr('disabled', 'disabled');
} else {
$('#groupunderwriter').removeAttr('disabled');
}
});
http://jsfiddle.net/T83vs/
I think prop is a better way to do it.
$("#groupunderwriter").prop("disabled", IsChecked);
Of course you can also use $("#checkbox").is(":checked") instead of IsChecked.
I cannot see any checkbox there, Anyway this is the simple jquery code to disable dropdown on checkbox checked.
$(function() {
$('#id_of_your_checkbox').change(function() {
if ($(this).is(':checked')) {
// disable the dropdown:
$('#id_of_dropdown').attr('disabled', 'disabled');
} else {
$('#id_of_dropdown').removeAttr('disabled');
}
});
});
I'm actually new to ajax and jquery, and I've started working on it only a few days ago. I have a jsp code like this :
<label>Choose the type of procedure you want :</label>
<select id="proc-type" name="proc-type">
<option value="selection">Select</option>
<option value="with-param">With parameters</option>
<option value="without-param">Without parameters</option>
</select>
<div class="drop" id="dropdown">
<label> Select Procedure (with parameters) : </label>
<select id="combobox" name="combobox">
<option>Proc1</option
<option>Proc2</option>
...
...
</select>
</div>
<div class="drop" id="drop">
<label> Select Procedure (without parameters) : </label>
<select id="combobox2" name="combobox2">
<option>Proc a</option
<option>Proc b</option>
...
...
</select>
</div>
<div id="response"></div>
Now, these values are sent to a servlet and a html response is generated. The ajax call I used is :
if first dropdown changes :
document.getElementById("combobox").onchange = function(){
var proc_type = document.getElementById("proc-type").value ;
var username = document.getElementById("combo").value ;
var proc_name1 = document.getElementById("combobox").value ;
var proc_name2 = document.getElementById("combobox2").value ;
console.log("before calling servlet ");
$.ajax({
url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
type : "GET",
dataType:"text/html",
success: function (data) {
console.log("in ajax "+ data);
$('#response').html(data);
}
});
};
if second dropdown changes :
document.getElementById("combobox2").onchange = function(){
var proc_type = document.getElementById("proc-type").value ;
var username = document.getElementById("combo").value ;
var proc_name1 = document.getElementById("combobox").value ;
var proc_name2 = document.getElementById("combobox2").value ;
console.log("before calling servlet ");
$.ajax({
url : "DBConnectServlet?user="+username+"&proc-type="+proc_type+"&combobox="+proc_name1+"&combobox2="+proc_name2,
type : "GET",
dataType:"text/html",
success: function(data) {
console.log("in ajax "+ data);
$('#response').html(data);
}
});
};
But problem is, the response is generated fine, but the div is not getting appended. Can anybody help ?
Even if there is some other way to do it, please suggest.
Try changing dataType to "text" or "html".There is no "text/html" in jquery manual about ajax on dataType.Good luck.