Populating a jquery array from values of a select using each - javascript

I'm trying to populate an array in Jquery with selected values from a select.
Here is my jquery (no ajax call because I first want to make the array before i call ajax to input fields into db)
$('#add-group-form').submit(function(e) {
e.preventDefault();
var contactsArr = [];
$("select option").each(function(i, val){
var $val = $(val);
if($(i).attr('selected', 'selected')){
contactsArr.push({value: $val.val()});
}
});
console.log(contactsArr);
});
Now in all honesty i got the each from a different source.
Not sure how i check the attribute to make sure it is selected.
Thanks in advance for the help
**EDIT:
Okay so I may have forgotten to check for answers as I got distracted by trying to figure it out
This is how I've done it (tested and works in my system).
var contactsArr = [];
$(".edit-contact-select option:selected").each(function() {
contactsArr.push({value: $(this).val()});
});
I was over-complicating the entire thing.

you don't need to iterate through options for the "selected" one. use this instead:
$('#add-group-form').submit(function(e) {
e.preventDefault();
var contactsArr = [];
$('select').each(function(){
contactsArr.push({value: $(this).val()});
});
console.log(contactsArr);
});
$('select').val() actually returns the SELECTED value of the select input.
hope that helps.

Looks like you have a multiple select if so you can use .val() to get the selected values in an array
$('#add-group-form').submit(function (e) {
e.preventDefault();
var contactsArr = $("select").val();
console.log(contactsArr);
});
If you want to store the selected values from multiple select elements, then use .map() like
$('#add-group-form').submit(function (e) {
e.preventDefault();
var contactsArr = $("select").map(function (i, val) {
return $(this).val()
}).get();
console.log(contactsArr);
});

Related

How to show all checked values in AJAX load checkbox group

I've checkbox list that load by ajax and I want to show the checked value in page while user checking each checkbox. Please see below image.
Hear That country and City load from the ajax according to the parent selection. Here there are 4 cites are checked and I want to show those all selected city values below the check boxes.
I've used below jquery code but it doesn't work.
$("#cites input[type='checkbox']").click(function(){
var checkedc = $(this).val();
$('#show_city').html(checkedc);
});
Use .on()
You have to use Event Delegation
Syntax
$( elements ).on( events, selector, data, handler );
like this
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
if (this.checked) {// check if the checkbox is checked
var checkedc = this.value;
$('#show_city').html(checkedc);
}
});
or
$('parentElementPresesntAtDOMready').on('click','#cites input[type="checkbox"]',function(){
// code here
});
Updated After OP's comment
.map()
$(document).on('change', '#cites input[type="checkbox"]', function () {
var checkedc = $('#cites input[type="checkbox"]:checked').map(function () {//use map to create array of checked elements
return this.value;
}).get().join(); //than join array with comma to string
$('#show_city').html(checkedc);
});
I'm completing Tushar's answer so that you get all the checked cities :
$(document).on('change', '#cites input[type="checkbox"]',function () { //better use change event
var listChecked = "";
if (this.checked) {// check if the checkbox is checked
if (this.checked) {
var value = $(this).val();
listChecked = listChecked + value + ";";
}
}
$('#show_city').html(listChecked);
});

Filter results of dropdownlist per prior dropdownlist selection using jquery

I successfully used the jquery script TheSuperTramp posted here:
Jquery dependent drop down boxes populate- how
to remove any list items with a value less than the one selected. However, I need to remove only the value I had selected in the first pull down menu. I believe the following jquery script should accomplish this however it is not. Any suggestions to correct this would be greatly appreciated.
Thanks,
KS
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').filter(function () {
if (parseInt(this.value) == drop1selected)
{
$(this).remove();
};
});
});
What you actually need here is .each(), instead of .filter():
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').each(function () {
if (parseInt(this.value) === drop1selected)
{
$(this).remove();
};
});
});
As .filter() will remove the element from the result set of matching elements, but it will not remove them from the DOM. You may want to use it like this:
var drop2 = $("select[id=dropdown] option"); // the collection of initial options
$("select[id=test]").change(function () {
var drop1selected = parseInt(this.value); //get drop1 's selected value
$("select[id=dropdown]")
.html(drop2) //reset dropdown list
.find('option').filter(function () {
return parseInt(this.value) === drop1selected;
}).remove();
});

Using Jquery to append form field's value to form action?

I have a simple form with a few textboxes on it. I would like to capture the input of the textboxes, modify it slightly and then append it to the form action URL.
$('.myBox').on('change', function (event) {
var myVal = $(this).val();
$('form').attr('action').appendTo("&MyVal="+myVal);
});
The above code doesn't work because there is no appendTo to the attr value. Is there another way to accomplish this?
Your syntax isn't quite right as you want to update the value of the action attribute, not append an element. Try this:
$('.myBox').on('change', function (event) {
var myVal = $(this).val();
$('form').attr('action', function(i, value) {
return value + "&MyVal=" + myVal;
});
});
You can try this one:
$("form").attr('action',$("form").attr('action')+ "&MyVal=test");
I actually came up with something similar.
$('.Mybox').on('change', function (event) {
var action = $('form').attr('action');
$('form').attr('action',action+"&test");
});
But I think I like yours better. Thanks

jquery binding to select changes

I have a hidden select which should be automatically selected via a visible select, my jquery is:
$(document).ready(function() {
var selected_val = $('#id_foo option:selected').val();
$('#id_bar').val(selected_val);
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
$('#id_bar').val(selected_val);
});
});
This works fine, but the page I am working on has the option to add a value to the (visible) select on the fly. How do I bind to this event and add this to the hidden list before updating the selected value?
The best way to tackle this is to update the hidden select with the new values when you update the visible one.
Or, as per my comment, you could populate the hidden select when the visible one is changed:
$("#id_foo").change(function() {
selected_val = $(this).attr('value');
//clear and re-populate all of hidden select here
$('#id_bar').val(selected_val);
});
This should do the trick:
$(function () {
var $bar = $('#id_bar');
var $foo = $('#id_foo');
$bar.val($foo.val());
$foo.change(function () {
var newValue = $(this).val();
if ($bar.find('[value="' + newValue + '"]').length === 0) {
$bar.append($('<option/>').val(newValue));
}
$bar.val(newValue);
});
});
Before setting the new value, checks if the value is an option. If it's not, add as an option.
This snippet correctly identifies the event and succesfully copies the select options from foo to bar. However it does not seem to set :selected correctly on either id_foo or id_bar and using DOMSubtreeModified feels hackish
$('#id_foo').bind("DOMSubtreeModified", function(){
var high = 0;
$('#id_foo').children().each(
function(){
if ($(this).val() > high) {
high = $(this).val();
}
}
);
$('#id_foo').val(high);
var new_options = $('#id_foo').clone();
$('#id_bar').html('');
$('#id_bar').append(new_options.children());
});
So, for now the best I could come up with:
$('#id_foo').bind("DOMSubtreeModified", function(){
location.reload();
});

How to build a simple table filter with jQuery?

How can I build a simple table filter with good effect using jQuery? I don't mind about pagination.
list -> select data of database.
I do not want to use a plugin, I prefer the use of short code.
Example:
$('#inputFilter').keyup(function() {
var that = this;
$.each($('tr'),
function(i, val) {
if ($(val).text().indexOf($(that).val()) == -1) {
$('tr').eq(i).hide();
} else {
$('tr').eq(i).show();
}
});
});
CHECH THIS
I don't normally help out with this, but I got bored this morning..
http://jsfiddle.net/hHJxP/
I know it's kinda late but hope this code helps.
<script>
$(document).ready(function(){
$("#yourInput").on("keyup", function() {
var value = $(this).val().toLowerCase();
$("#yourTableId tr").filter(function() {
$(this).toggle($(this).text().toLowerCase().indexOf(value) > -1)
});
});
});
</script>
Try testing the innerHTML of the row to the value of the input field, showing / hiding the content depending on the test-result.
$('#test').bind('keyup', function() {
var s = new RegExp(this.value);
$('tr').each(function() {
if(s.test(this.innerHTML)) $(this).show();
else $(this).hide();
});
});
JSFIDDLE with example table and input field.
edit
It might be better to use .text() instead of innerHTML. Performancewise innerHTML would be better, but .text() doesn't accept the html-tags as valid search results. JSFIDDLE #2.

Categories