The whole idea is to limiting the number checkboxes through dropdown, the approach is:
I have dropdown with following code
<select name="form[norequnit][]" id="norequnit" class="rsform-select-box">
<option value="">...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>01</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>02</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>03</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>04</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>05</label>
<input name="chk" type="checkbox" class="bd-lable" value="9432"><label>06</label>
And some check boxes which are loading by ajax and below code is running to get dropdown value and also after ajax part to limit the number of selection based on the selected dropdown,
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#norequnit").on("change", function () {
$('#unitcount').html($(this).find('option:selected').text());
});
$( document ).ajaxComplete(function() {
$( ".log" ).text( "Triggered ajaxComplete handler." );
var nux = $('#unitcount').text();
$("input[name=chk]").change(function(){
var max= nux;
if( $("input[name=chk]:checked").length == max )
{
$("input[name=chk]").attr('disabled', 'disabled');
$("input[name=chk]:checked").removeAttr('disabled');
}
else{
$("input[name=chk]").removeAttr('disabled');
}
})
});
});
</script>
Problem:
variable "nux" get value only in first attempt by selecting dropdown, for example 5 so you to limit the boxes to 5 checks, but after this if you change dropdown to any other number the checkbox limitation remains on 5, in other word "nux" wont get new variable.
There's a few things wrong with your code, I'll try and go through them piece by piece with explanations and fixes.
Select onChange handling:
Separate your data from your view
Use val() instead of text() to get a select's current value
Code:
var nux; // 1. This will hold the value of nux for use in your script
$("#norequnit").on("change", function () {
nux = $(this).val(); // 1. Save the data, 2. Use using val()
$('#unitcount').html(nux); // 1. Use the data
});
Do you really need to use ajaxComplete?
I don't think ajaxComplete is the right way to go about responding to an ajax call (I could be wrong, I don't have all your code in front of me). Below I've done a best guess as to what you should (maybe, probably) do.
Code:
// Assuming you've got your ajax call somewhere else, use the "success"
// handler instead of the "ajaxComplete" function
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
// Presumably this is the HTML for your checkboxes, so add them
// to the DOM
$('#norequnit').after(html);
// And the only thing that really should go here otherwise is
// your bit of debug logging
console.log("Triggered ajax success handler.");
}
});
Use console.log if you are just outputting debug text
Maybe you actually do want to print the message on the page, if so you can ignore this. At very least, be aware of this wonderful debug-enabling tool. You can hit F12 (developer console) in your browser to view the output.
console.log("Triggered ajaxComplete handler.");
Move your checkbox onChange handler outside of any ajax closures
You could run into some incredibly hard to debug issues otherwise.
Code:
$(document).on('change', 'input[name="chk"]', function() {
// Handler code here
});
Notice the slightly different call to on, which uses the document object and includes the context parameter. This ensures any objects added to the DOM after the event handler is registered will still be handled.
All of it together
jQuery(document).ready(function($) {
var nux;
$("#norequnit").on("change", function () {
nux = $(this).val();
$('#unitcount').html(nux);
});
$.ajax({
url: yourUrl,
method: 'get',
data: {
param1: 'value1',
param2: 'value2', // etc
},
success: function(html) {
$('#norequnit').after(html);
console.log("Triggered ajax success handler.");
}
});
$(document).on("change", 'input[name="chk"]', function() {
if ($('input[name="chk"]:checked').length == nux) {
$('input[name="chk"]').attr('disabled', 'disabled');
$('input[name="chk"]:checked').removeAttr('disabled');
// Alternatively you could do this:
$('input[name="chk"]').not(':checked').attr('disabled', true);
} else {
$("input[name=chk]").removeAttr('disabled');
}
});
});
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi i want to manage data on drop-down menu using Ajax.
Databse Fields:
1.id
2.name
3.department
myDesgin.php
<select id="id"></select>
<select id="name"></select>
<select id="department"></select>
1.If i selected one drop-down menu want to change another drop-downs depend on selected value using Ajax.
2.Is there any code available, if i select one drop-down it go to another child window and display data as in table format(like report) using Ajax.
Thanks in Advance.
Please give me example code, because i am beginner to ajax , most welcome if someone provide explanation with code(for ajax).
Yes, check following jquery ajax code.
In this example, if you change "Department" then it will populate the listing of "Name" dropdown.
$(document).on("change", '#department', function(e) {
var department = $(this).val();
$.ajax({
type: "POST",
data: {department: department},
url: 'admin/users/get_name_list.php',
dataType: 'json',
success: function(json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
I guess you can do this:
make a global function which accepts two args, currElem, nextElem and dataObj:
function dynoDropdowns(currElem, nxtElem, dataObj){
$.ajax({
url:"path/to/file",
type:"post",
data:dataObj,
dataType:"json", // <-------------expecting json from php
success:function(data){
$(nxtElem).empty(); // empty the field first here.
$.each(data, function(i, obj){
$('<option />',
{
value:obj.value,
text:obj.text
}
).appendTo(nxtElem);
});
},
error:function(err){
console.log(err);
}
});
}
now your change events are:
$(function(){
$('select').on('change', function(e){
if(this.id === "id"){
var dataObj = {id:this.value};
dynoDropdowns(this, '#name', dataObj);
}else if(this.id === "name"){
var dataObj = {name:this.value};
dynoDropdowns(this, '#department', dataObj);
}
});
});
given select1 and select2 like this:
<select id="select1">
<option id="11" value="x">X</option>
<option id="12" value="y">Y</option>
</select>
<select id="select2">
<option id="21" value="1">1</option>
<option id="22" value="2">2</option>
</select>
then you can do something like this with jQuery:
$('#select1').on('change', function() {
$.ajax({
url: "test.html",
}).done(function(response) {
$('#select2').html(response);
});
This assumes your ajax call returns a string like
<option id="21" value="3">3</option><option id="22" value="4">4</option>
from your server sided file. If you return a json you have to decode it first, but this is the general gist of it. Take a look at the jQuery ajax() function
Although there are many codes available out there. I am writing most easy and basic code for you.
HTML
<select id="id" onchange="update_name(this.id)"></select>
AJAX Code
function update_name(id)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_data.php?q="+id,true);
xmlhttp.send();
}
update_data.php (PHP code)
<?php
if(isset($_GET['q'])
{
$id= $_GET['q'];
//based on id run your query
}
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Hi i want to manage data on drop-down menu using Ajax.
Databse Fields:
1.id
2.name
3.department
myDesgin.php
<select id="id"></select>
<select id="name"></select>
<select id="department"></select>
1.If i selected one drop-down menu want to change another drop-downs depend on selected value using Ajax.
2.Is there any code available, if i select one drop-down it go to another child window and display data as in table format(like report) using Ajax.
Thanks in Advance.
Please give me example code, because i am beginner to ajax , most welcome if someone provide explanation with code(for ajax).
Yes, check following jquery ajax code.
In this example, if you change "Department" then it will populate the listing of "Name" dropdown.
$(document).on("change", '#department', function(e) {
var department = $(this).val();
$.ajax({
type: "POST",
data: {department: department},
url: 'admin/users/get_name_list.php',
dataType: 'json',
success: function(json) {
var $el = $("#name");
$el.empty(); // remove old options
$el.append($("<option></option>")
.attr("value", '').text('Please Select'));
$.each(json, function(value, key) {
$el.append($("<option></option>")
.attr("value", value).text(key));
});
}
});
});
I guess you can do this:
make a global function which accepts two args, currElem, nextElem and dataObj:
function dynoDropdowns(currElem, nxtElem, dataObj){
$.ajax({
url:"path/to/file",
type:"post",
data:dataObj,
dataType:"json", // <-------------expecting json from php
success:function(data){
$(nxtElem).empty(); // empty the field first here.
$.each(data, function(i, obj){
$('<option />',
{
value:obj.value,
text:obj.text
}
).appendTo(nxtElem);
});
},
error:function(err){
console.log(err);
}
});
}
now your change events are:
$(function(){
$('select').on('change', function(e){
if(this.id === "id"){
var dataObj = {id:this.value};
dynoDropdowns(this, '#name', dataObj);
}else if(this.id === "name"){
var dataObj = {name:this.value};
dynoDropdowns(this, '#department', dataObj);
}
});
});
given select1 and select2 like this:
<select id="select1">
<option id="11" value="x">X</option>
<option id="12" value="y">Y</option>
</select>
<select id="select2">
<option id="21" value="1">1</option>
<option id="22" value="2">2</option>
</select>
then you can do something like this with jQuery:
$('#select1').on('change', function() {
$.ajax({
url: "test.html",
}).done(function(response) {
$('#select2').html(response);
});
This assumes your ajax call returns a string like
<option id="21" value="3">3</option><option id="22" value="4">4</option>
from your server sided file. If you return a json you have to decode it first, but this is the general gist of it. Take a look at the jQuery ajax() function
Although there are many codes available out there. I am writing most easy and basic code for you.
HTML
<select id="id" onchange="update_name(this.id)"></select>
AJAX Code
function update_name(id)
{
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txt").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","update_data.php?q="+id,true);
xmlhttp.send();
}
update_data.php (PHP code)
<?php
if(isset($_GET['q'])
{
$id= $_GET['q'];
//based on id run your query
}
need your help for this ... My homepage have 3 divs, #Header, #Content, #Footer. All the other pages are being opened inside the #Content div. In one of those pages I have a form with two select lists and one submit button. Just want to click the button and then return another page into the #Content div, showing the values that I select before. Like this:
The origin is: 1
The destiny is: 1
But this code returns the following ...
Notice: Undefined variable: origin in ...
Notice: Undefined variable: destiny in ...
Note: This is working if I don't open the page inside the #Content div
my Html:
<form id="myform" name="myform" action="values.php" method="POST">
<select id="origin" name="origin">
<option value="0" selected>-- Select Origin --</option>
<option value="1">Portugal</option></select>
<select id="destiny" name="destiny">
<option value="0" selected>-- Select Destiny --</option>
<option value="1">Lisboa</option></select>
<input id="btSubmit" name="btSubmit" type="submit" value="search!">
</form>
my Function:
$(document).ready(function(){
$('#btSubmit').click(function(e) {
e.preventDefault();
var url = $('#myform').attr('action');
var method = $('#myform').attr('method');
$.ajax({
type: method,
url: url,
data: $('#myform').serialize(),
success: $('#content').load(url)
});
});
});
my values.php page:
<?php
if(isset($_POST['origin']) || isset($_POST['destiny']))
{
$origin = $_POST['origin'];
$destiny = $_POST['destiny'];
}
echo 'The origin is:' . $origin . '<br>';
echo 'The destiny is:' . $destiny;
?>
You should not call load again - you have already called it essentially with $.ajax and received the results. So you need just display them in the content:
success: function (data) {
$('#content').html(data);
}
You should use success callback function correctly. Accept response in callback method and set it in your div
success: function (data) {
$('#content').html(data);
}
Additionally, You should perform your operation with form submit event.
$('form#myform').on('submit', function (e) {
instead of
$('#btSubmit').click(function(e) {
As Andrei mentioned you have to use
success: function (data) {
$('#content').html(data);
}
because calling success: $('#content').load(url) triggers a new GET request. When GET request reaches php code $_POST is not set and your variables are not initialized so you get the message from php:
Notice: Undefined variable: origin in
Ok I have a onchange event on a select field. It now works great. When the dropdown "networks" is changed it refreshes the second dropdown. I also want the ajax code at the top to trigger on page load as well as onchange so the second list gets populated. This is due to it being on an edit page. Here is the ajax call im using first
function get_cities(networks) {
$.ajax({
type: "POST",
url: "select.php", /* The country id will be sent to this file */
beforeSend: function () {
$("#folder").html("<option>Loading ...</option>");
},
//data: "idnetworks="+networks,
data: "idnetworks="+networks +"&doc="+ <?php echo $row_rs_doc['parentid']; ?>,
success: function(msg){
$("#folder").html(msg);
}
});
}
now the two dropdown boxes
<label for="networks"></label>
<select name="networks" id="networks" onChange='get_cities($(this).val())'>
<?php
do {
?>
<option value="<?php echo $row_rs_net['idnetworks']?>"<?php if (!(strcmp($row_rs_net['idnetworks'], $row_rs_doc['network']))) {echo "selected=\"selected\"";} ?>><?php echo $row_rs_net['netname']?></option>
<?php
} while ($row_rs_net = mysql_fetch_assoc($rs_net));
$rows = mysql_num_rows($rs_net);
if($rows > 0) {
mysql_data_seek($rs_net, 0);
$row_rs_net = mysql_fetch_assoc($rs_net);
};
?>
</select>
<select name="folder" id="folder">
</select>
You can use .trigger() to trigger a change event onto the select-box so the onchange code will be called like it would if the user just switched the option.
jQuery('#networks').trigger('change');
Just include this into the load event/function for the page.
jQuery(document).ready(function() {
jQuery('#networks').trigger('change');
});
I'm not 100% clear what you want but the standard way to do something with JQuery when the page is loaded, is to use
$(document).ready(handler)
This waits till the page is "ready" which is better.
So, in your document head you'd have something like this...
<script type="text/javascript">
$(document).ready( function(){
do_some_stuff();
});
</script>
Can't you just call get_cities($('#networks').val()) when the DOM is ready?
$(function() { // will be run by jQuery when DOM is ready
get_cities($('#networks').val());
});
Im trying to trigger an asynchronous JSON request when I select an option from an HTML selector box using mootools.
I have the following form element:
<form method="post" id="sel">
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
</form>
I'm using the following javascriipt/mootools to send a JSON request carrying the form info
window.addEvent('domready', function()
{
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response)
{
$('response').set('html', response.params)
}
}).get($('sel'));
})
});
to the following php script
$result['params'] = $_GET;
echo json_encode($result);
However, I'm told in Chrome's developer tools 'cannot read property "params" of null'
I don't see why request should be 'null' here.
Any ideas would be greatly appreciated
Hey man the answer to your question is in the question itself.
Your triggering the event when you are clicking on the select when like you said "select an option"
Click on the select would be wrong, however so would click on an option with in the select what your looking for is the onChange event the code would be as follows:
HTML
// Notice no form tag needed unless you are serializing other items
<select id = "_selecor_id" size=3>
<option value = "value_a" id = "option_a">OptionA</option>
<option value = "value_b" id = "option_b">OptionB</option>
</select>
<p id="response"></p>
JAVASCRIPT
window.addEvent('domready', function(){
$('_selecor_id').addEvent('change', function(){
new Request.JSON({ // This must return a valid json object
url: "my_php_script.php",
data: {
'value': this.get('value')
}
onSuccess: function(responseJSON, responseText){
$('response').set('html',responseJSON.params);
}
}).send();
})
});
PHP
$result['params'] = isset($_GET['value']) ? $_GET['value'] : 'Not Set';
echo json_encode($result);
The responseJson variable will now contain something like {"params":"value_b"}
Try this code:
window.addEvent('domready', function(){
$('_selecor_id').addEvent('click', function(){
new Request.JSON({
url: "my_php_script.php",
onSuccess: function(response){
$('response').set('html',(response || this.response || this.responseText || {params: ''}).params)
}
}).get($('sel'));
})
});