So I have a 2 multiple select box (one for the floor and one for the room). The values in the Room depends on the Floor. If you choose Floor: 001 all the values in the Room will start on 1 and if you choose Floor: 002 all the values in the Room will start in 2, and so on. But when I select the values in the Room all of the values will disappear, here's my script:
<script type="text/javascript">
$(document).ready(
function()
{
var selectArr = [];
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
function clearArray() {
return selectArr = []
}
function populateRooms() {
$.ajax({
type: "GET",
url: "/hms/shifts/" + selectArr,
success: function (response) {
$('#_rooms_id').empty();
var myObject = eval('(' + response + ')');
for (i in myObject)
{
$('#_rooms_id').append(
$('<option></option>',
{
value: myObject[i]["id"],
text: myObject[i]["roomNumber"]
}
)
);
}
},
error: function (e){
alert("Error" + e)
}
});
}
});
</script>
I think it's because of the .empty() but if I remove that all of the values in room will show, there will be no filter. I hope someone can help me. Newbie here. Thank you.
I guess you should add the event to populate rooms-select only in the floor-select
This code add the onChange event to ALL dropdowns in your code:
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
Change to this:
$("#floors-dropdownId").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
You have applied generic 'change' event on all select which causes it to clear.
//you have issue here , $(select) means all selects in your current DOM!
$("select").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
Chang to ,
// Apply change on specific instead
$("select#floorId").change(function(){
var arr = $(this).val()
selectArr.push(arr);
console.log(arr)
populateRooms();
clearArray();
});
Related
I've tried lot's of solutions here before actually make this question but none of them has worked for me.
I've tried to use onclick handler, tried to get by input name, tried getElementId, tried elementClassName also i tried to loop them var i = 0, length = radios.length; i < length; i++ none has worked for me!
Logic
My radio buttons will append to view based on ajax action
I select any of this radio buttons
And i want get values of this selected radio button
Code
This is how my radios append I made it short to be clean and easy to read
success:function(data) {
$('.shipoptions').empty();
$('.shipoptionstitle').empty();
$('.shipoptionstitle').append('<h6>Select your preferred method</h6>');
$.each(data.data, function(key, value) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('.shipoptions').append('<ul class="list-form-inline"><li><label class="radio"><input type="radio" name="postchoose" data-code="'+value['code']+'" data-service="'+value2['service']+'" value="'+ value3['value'] +'"><span class="outer"><span class="inner"></span></span>'+ value['code'] + ' - ' + value2['service'] + ' - Rp ' + nf.format(number) + ' - ' + value3['etd'] +'</label></li></ul>');
});
});
});
} //success function ends here
Now I want to get selected radio button values of data-code ,
data-service and value
For the temporary please just help me to get those values in console, later I'll fix the printing part myself.
Any idea?
<input type="radio" name="postchoose" data-code="'DC11'" data-service="'DS22'" value="'V33">
var dataCode = $('input[name="postchoose"]:checked').data('code');
var dataService = $('input[name="postchoose"]:checked').data('service');
var selectedVal= $("input:radio[name=postchoose]:checked").val();
SOLVED
$(function() {
$(".shipoptions").on('change', function(){
var radioValue = $("input[name='postchoose']:checked");
if(radioValue){
var val = radioValue.val();
var code = radioValue.data('code');
var service = radioValue.data('service');
alert("Your are a - " + code + "- " +service+ "- " +val);
}
});
});
I needed to get a higher class of my radio buttons .shipoptions
Try this jQuery Method.
$("input[type='radio']").click(function() {
var radioValue = $("input[name='postchoose']:checked").val();
var dataCode = $("input[name='postchoose']:checked").attr('data-code');
var dataService = $("input[name='gender']:checked").attr('data-service');
console.log(dataCode);
console.log(dataService);
console.log(radioValue);
});
I have an input field with Add button below it. Also have another Div class named .new-option-content
What I am trying to do is if anyone type something in the input filed and click the +ADD button this text of the input filed will append with a Check box inside .new-option-content div.
Here is the Fiddle
I tried with this but I guess with this process I can't get the result.
$( ".checklist-new-item-text" )
.keyup(function() {
var value = $( this ).val();
$( ".new-option-content" ).text( value );
})
.keyup();
I am not good with advance jquery. I did tried to find something similar but failed. I am not sure if this can be done with jquery.
Any help or suggestion will be appreciated.
$("#add").click(function(){
var newLabel = $("#optionInput").val();
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
$(".new-option-content").append(newOption);
$("#optionInput").val(''); //clearing value
})
Fiddle: http://jsfiddle.net/has9L9Lh/8/
If you want to use it in multiple places on your page, you can try this modified version:
$(".new-option-add").click(function(){
var labelInput = $(this).parent().parent().find(".checklist-new-item-text")
var newLabel = labelInput.val()
if (!newLabel) return; //avoid adding empty checkboxes
var newOption = '<div class="checkbox"><label><input type="checkbox">' + newLabel +'</label></div>';
// where to append?
var listToAppend = $(this).attr("data")
$("." + listToAppend).append(newOption);
labelInput.val(''); //clearing value
})
We are using data attribute value on the button, to assign class name of the list, which need to be updated.
Fiddle: http://jsfiddle.net/has9L9Lh/18/
Here is how you can do it:
$(function() {
$('.new-option-add').on('click',function() {
var noc = $('.new-option-content'),
val = $('.checklist-new-item-text');
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
And this should work for multiple sections:
$(function() {
$('.new-option-add').on('click',function() {
var section = $(this).closest('section'),
noc = $('.new-option-content', section),
val = $('.checklist-new-item-text', section);
!val.val() || noc.append(
$('<div/>',{class:'checkbox'}).html(
$('<label/>').html( $('<input/>', {type:'checkbox'}) )
.append( ' ' )
.append( val.val() )
)
);
val.val('');
});
});
DEMO
Many have answered, yet another option is to use .clone(), cause otherwise you can end up in a maintainence nightmare, so something like
$(".new-option-add").click(function() {
var checkbox = $(".checkbox:first").clone(), value;
value = $(".checklist-new-item-text").val();
checkbox.html(checkbox.html().replace('Sample 1', value));
checkbox.appendTo($(".new-option-content"));
})
http://jsfiddle.net/has9L9Lh/19/
you can do this by adding this code
on click event
$('#yourDiv').append(' <label><input id="chkbox" type="checkbox"> "+$('#yourText').val() +" </label>');
I am having an issue where the current state of the checkbox is not being saved. I am new to this and any help would be appreciated. Here's the jQuery code that is partially working.
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
userCityList.push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
userCityList.pop();
}
//console.log(userCityList);
});
LOGIC
When the user selects a state, a set of cities in checkboxes appear. When a user clicks a checkbox, that particular city is stored in the userCityList array. When the user clicks it again, it deletes it from the array. However, if the user changes the state, those cities are no longer checked, which does not allow one to delete it from the array, if needed.
Any suggestions?
HTML code
<div class="panel-body">
<p>Select upto 5 state/city combinations</p>
<div class="col-xs-3 no-pad-left less-width">
#*<p>Select upto 5 state/city combinations</p>*#
<select id="ResidentialLocationStateList" name="ResidentialLocationStateList" multiple></select>
</div>
<div class="col-xs-3" id="checkboxes">
</div>
</div>
UPDATE Here's the image that goes with this issue.
So when a few cities are selected and the user decides to change the state from the select element, those cities that were selected prior need to be saved.
UPDATE
Here's the AJAX code...
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
});
});
});
If you're using a modern version of jQuery I would recommend using .off and .on and to use .off if you really have to.
lso the .pop() array method removes the last element but the element just clicked may not always be the one that was added last. And since, the check boxes are added dynamically, the following bind could be made at the very beginning of DOM ready and not necessarily in any event handler. Rather than give your checkboxes the same ID which leads to invalid HTML, use a class selector, .checkboxes.
Therefore, I would suggest the following code
var userCityList = [];
$(document).on("change", ".checkboxes", function() {
var stateVal = $('#ResidentialLocationStateList').val();
var cityID = this.id;//stores city id
var cityVal = this.value;//stores city value
var finalDiv = $('#final');
var tempDiv = $('#othertempdiv');
if( this.checked ) {
if( userCityList.length < 5 ) {
userCityList.push( cityID );
finalDiv.append( this );
} else {
$(this).prop('checked', false);
alert('5 cities have been selected');
}
} else {
var index = $.inArray( cityID, userCityList );
if( index > -1 ) {
userCityList.splice( index, 1 );
tempDiv.append( this );
}
}
});
Since you're -- per comments below -- replacing the selected cities each time you select a new state, you would have to have a second div which would hold all the selected cities. Un-checking any of the cities in this final div would move it back; if another state is selected, such a city would be lost.
<div id="final"></div>
Use a multidimensional array to store both state and city IDs, like userCityList [ stateVal ]:
var userCityList = [];
$("#checkboxes").unbind('change').bind('change', function (event) {
var stateVal = $(':selected', $('#ResidentialLocationStateList')).val();
var cityID = $(event.target)[0].id;//stores city id
var cityVal = $(event.target)[0].value;//stores city value
if ($('#' + cityID).is(':checked')) {
if (userCityList.length < 5) {
if(!userCityList[stateVal])userCityList[stateVal] = [];
userCityList[stateVal].push(cityID);
}
else {
$('#' + cityID).prop('checked', false);
alert("5 cities have been selected");
return;
}
}//end if
if (!($("#" + cityID).is(':checked'))) {
if(userCityList[stateVal]){
//Edited, now it can remove the city by its position (index)
var position = $.inArray(cityID, userCityList[stateVal]);
userCityList[stateVal].slice(position, 1);
}
}
});
So when you need to retrieve the checked cities for an state you can do just:
for(var i =0; i < userCityList[stateVal].length; i++){
console.log(userCityList[stateVal][i]);
}
UPDATE
The hard work is done. Now, in your ajax code, when you load a new set of checkboxes, you have to check if the checkbox was previously checked:
$("#ResidentialLocationStateList").change(function () {
url = "/ResidentialBuilding/getCityList?state=";
state = $("#ResidentialLocationStateList").val();
url = url + state;
//console.log(url);
$("#checkboxes").empty();
$.getJSON(url, function (data) {
//console.log(data);
$.each(data, function (index, value) {
//console.log(value.city);
id = value.city;
id = id.replace(/\s+/g, '');
valCity = value.city;
valCity = valCity.replace(/\s+/g, '');
$("#checkboxes").append('<input value="' + valCity + '"' + 'type=' + "'checkbox'" + 'id=' + id + '>' + value.city + '</input><br>');
//Let's check if this checkbox was previously checked
if($.inArray(id, userCityList[state])){
//if yes, let's check it again
$('#'+id).prop('checked', true);
}
});
});
});
Keep in mind that the userCityList variable must be global to store these values and you will loose your checkboxes memories if you refresh the page, of course.
I modified the simple example of jQuery.post as
$("#searchForm").submit(function(event) {
event.preventDefault();
var $form = $( this ),
term = $( "input[name^=tick]:checked" ).serialize(),
url = $form.attr( 'action' );
$.post( url, { ticks: term, id: '55' },
function( data ) {
$( "#result" ).empty().append( data );
}
);
});
This works for single checkbox with val() but not for multiple checkboxes in
<input type="checkbox" name="tick" value="'.$value.'" />
since serialize() should generateticks: termto be used astermin$.post`.
How can I make the serialize() to generate appropriate data for $.post
NOTE: I do not want to serialize the entire form but only checked values of checkbox INPUT.
Simple value collector :)
HTML
<input type="checkbox" class="selector" value="{value}"/>
JS
var checked='';
$('.selector:checked').each(function(){
checked=checked+','+$(this).val();
});
PHP
$ids=explode(',',substr($_GET['param_with_checked_values'],1));
You could use .serializeArray()
Ref: http://api.jquery.com/serializeArray/
In html code change name="tick" in name="tick[]" and you can use simply $(this).serialize(); to post all checked values.
You can still use .serializeArray and use it in .post() like this:
var postData = {};
var form = $('#formId').serializeArray();
for (var i = 0; i < form.length; i++) {
if (form[i]['name'].endsWith('[]')) {
var name = form[i]['name'];
name = name.substring(0, name.length - 2);
if (!(name in postData)) {
postData[name] = [];
}
postData[name].push(form[i]['value']);
} else {
postData[form[i]['name']] = form[i]['value'];
}
}
$.post('/endpoint', postData, function(response) {
}, 'json');
postData will contain all form elements except the disabled ones. All checkbox values will be passed as an array just like when doing a normal form submission.
let $form = $(".js-my-form");
let $disabled = $form.find(':input:disabled').removeAttr('disabled');
let formData = {};
$.each($form.serializeArray(), function (index, fieldData) {
if (fieldData.name.endsWith('[]')) {
let name = fieldData.name.substring(0, fieldData.name.length - 2);
if (!(name in formData)) {
formData[name] = [];
}
formData[name].push(fieldData.value);
} else {
formData[fieldData.name] = fieldData.value;
}
});
$disabled.attr('disabled', 'disabled');
console.log(formData);
Its a variation of Stanimir Stoyanov answer with possibility to serialize disabled fields.
term = $("#input[name^=tick]:checked").map(function () {
return this.value;
}).get();
term.join();
I have a problem, i have X <input type="checkbox" /> in my code, now I want to foreach this object/array its out put. - look my code.
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
alert( $("input[#id=selectname]:checked").val() ); //submit the form
}
});
function isCheckedById(id)
{
var checked = $("input[#id="+id+"]:checked").length;
if (checked == 0)
{
return false;
}
else
{
return true;
}
}
When I output it in alert i get a object, but if I have select 2 checkbox I what the value in this 2 checkboxes.
I hope I can be helpful and all here understand me :)
How about
$("#denied_seekrs").click(function() {
var checkedInputs = $("input:checked");
var test = "";
$.each(checkedInputs, function(i, val) {
test += val.value+",";
});
test = test.substring(0,(test.length-1));
alert(test);
});
I'm not exactly sure what you're looking for, but I'm guessing that the jQuery.each() method will help. You can use it to iterate over arrays, objects, and more.
var arr = [ "one", "two", "three", "four", "five" ];
jQuery.each(arr, function() {
$("#" + this).text("My id is " + this + ".");
return (this != "four"); // will stop running to skip "five"
});
how about something like this:
jQuery.each(checked, function() {
$(checked + this).text("My id is " + this + ".");
});
Can it be that - ultimately - you are looking for $.serializeArray() or $.serialize()?
If not, then maybe this is helps you:
$("#denied_seekrs").click(function()
{
if (!isCheckedById("selectname"))
{
alert ("Please select at least one event");
return false;
}
else
{
// prepare array of values
var values = [];
// prepare list of checked checkboxes
var $checkboxes = $("input[#id=selectname]:checked");
// push each individual value into the array
$checkboxes.each(function() { values.push( $(this).val() ); });
// debug output
alert( values.join("\n") );
//submit the form
}
});
When I got you right, you want the user to select one checkbox (or is it one or more?). This should do it:
$("#denied_seekrs").click(function()
{
var $checkedInputs = $("input:checked");
if ($checkedInputs.length != 1)
{
alert ("Please select one event");
return false;
}
alert( $checkedInputs.val() ); //submit the form
});
EDIT:
After reading your question again, I realized that the above code does not answer your question. However, the above does work and is a much shorter version of your solution. Maybe you want to use it instead. To answer your question, you could alert the value of all checked boxes like this:
Change this:
alert( $checkedInputs.val() ); //submit the form
to this:
var values = "";
$checkedInputs.each(function(){
values += $(this).val() + " ";
});
alert( values );