jQuery loop giving all <select> options instead of option:selected - javascript

There is a table that I need to loop through and get the values from, then store them in an array. Right now this loop is giving me all the values, however when it encounters an HTML < select> element it returns the selected option then it gives me all of the select options. I only want the selected option, not the entire list.
This is much easier to explain by showing you. So here is the fiddle and here is the jQuery code
var saveEdits = [];
$('#save').click(function () {
$('.projects_editable_tbody tr').each(function () {
$('.projects_editable_content_td, option:selected', this).each(function () {
var $input = $("input", this);
if ($input.length) {
saveEdits.push($input.val());
} else saveEdits.push($(this).text());
});
});
$.each(saveEdits, function (index, value) {
console.log(index + ': ' + value);
});
});
As you can see from the fiddle the array is populating almost exactly like I want it to. Any help is appreciated. If you need more info/code just let me know.

It's giving you the text from the td that contains the select, because you've specified .projects_editable_content_td. You need to exclude the .projects_editable_content_td that contain a select. See the code I posted to your question from yesterday.

Perhaps I misunderstood the question, but I tinkered with your code to push the current selected value of each select, instead the select itself. I also edited the content of the select boxes to use "selected" prop.
$('.projects_editable_content_td', this).each(function () {
if(jQuery(this).children().val()) {
saveEdits.push($(this).children().val());
} else {
saveEdits.push(jQuery.trim($(this).text()) );
}
});
You can see in this jsfiddle
http://jsfiddle.net/amenadiel/WNSBk/29/
The first row is edited and it returns a correct array. The second one was left as it was and still has the problem.
In your scenario it would probably be better if you enclosed each line in tags and harvest the data using the serialize() method of the form. For this you would need to make every field an input. For example, you could put a hidden field next to text elements.

Related

Jquery in loop to perform some calculation of records

Iam trying to bring some records using php and do some calculations. What iam doing now is that, each rows is having a dropdown with different currencies. When i select each currency, it calculates and shows certain values. Till here its working fine.
What i am trying to achieve is that if i select first currency dropdown, it should calculate the complete records calculations instead of selecting the currency of each rows. I guess i need to do some kind of loop in the jquery which calculates the rows.
Fiddle
Following is the part of jquery script for the currency dropdown.
$(window).load(function() {
$(document).ready(function() {
$("select").on('change', function() {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
var selected = $(this).find('option:selected').text();
if (selected == "INR") {
$(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
} else {
$(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
}
$(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val() / $(this).closest('table').find('.qty').val()).toFixed(3));
});
});
});
i guess i need to add some loops here in this jquery. Anyone to guide me how to do this. Or i need to follow a different step.
This is what i have tried as per the suggestion from Leonix.
$(document).ready(function(){
$(this).closest('table').find("select").each(function() {
var dept_number = $(this).val();
var price = $(this).find(':selected').data('price');
var selected = $(this).find("select");
if(selected=="INR")
{
$(this).closest('table').find('.total1').val($(this).closest('table').find('.total').val());
} else
{
$(this).closest('table').find('.total1').val((($(this).closest('table').find('.total').val() * price) / $(this).closest('table').find('.inrvalue').val()).toFixed(3));
}
$(this).closest('table').find('.price_unit').val(($(this).closest('table').find('.total1').val()/$(this).closest('table').find('.qty').val()).toFixed(3));
});
});
In your select change function, do a each for all rows of your table and find the dropdown:
$(this).closest('table').find("select").each(function() {
/* Each SELECT here, use $(this) */
})
or, depending of your needs :
$(this).closest('table').find("select").each(function() {
/* Each TR here, use selectInput */
var selectInput = $(this).find("select");
})
With the select in hands, use selectInput.val(changedSelectInput.val())
changedSelectInput is the jquery object containing the select who changed.
Using nested anonymous functions, take care, they are executed in the object context, so this and $(this) change depending on the object affected by function.
Advice: Use specific css classes for JS, as select.select-currency instead of select only, put these classes in your code. it will prevent so many mistakes and will save your time.
Note: currency_change[] is not a valid ID, if you dont need to set one, dont.
EDIT
Some code: https://jsfiddle.net/btpxq5ow/6/
What I did ?
Fix tags issues
Fix input in tbody issues, NEVER put it in a tr, tbody, table directly.
Fix some indentation issues
Apply the currency change to all rows
Prevent change event to call itself in an infinite loop
Apply calculation to all rows when they are updated
Fix some code syntax & performance issues
Please check your calculation are right since i modified it, see calculateRowTotals().
There are still a few html/js errorsthat must be fixed.
You will rarely get code from stackoverflow

Html select not changes option on click after jquery instant filter in jsp

I have 3 select tags on one page, generated from struts2 select tag. I am using a jQuery filter function that filters the select. One textfield for every select, but all of them use the same filter function. I have another js function that is called on onChange event.
The problem is that before adding this jQuery function i was filtering the lists with form submit and reload the page and now the filtration happens instant, but when i write a filtration criteria the select somehow the select loses focus and when i click an element no select happens, or better lets say is a kind of select: the element is circled with a dotted line, not selected with a blue filled square. The js is called, the form submitted, but with the old value. However, if i first click in the select where are no elements (empty zone) and then i select an element everything is ok. How can i jump over the firs click?
And now my code:
I. The jQuery filter function and the binding to the selects and textfields.
jQuery.fn.filterByText = function(textbox) {
return this.each(function() {
var select = this;
var options = [];
$(select).find('option').each(function() {
options.push({value: $(this).val(), text: $(this).text()});
});
$(select).data('options', options);
$(textbox).bind('change keyup', function() {
var options = $(select).empty().scrollTop(0).data('options');
var search = $.trim($(this).val());
var regex = new RegExp(search,'gi');
$.each(options, function(i) {
var option = options[i];
if(option.text.match(regex) !== null) {
$(select).append($('<option>').text(option.text).val(option.value));
}
});
});
});
};
$(function() {
$('#selectedClientId').filterByText($('#filterClient'));
$('#selectedLocationId').filterByText($('#filterLocation'));
$('#selectedViewPointId').filterByText($('#filterViewpoint'));
});
II. One of the selects:
<s:select size="10" cssStyle="width:220px;"
label="Select a client"
listKey="id" listValue="name"
list="clientSelectList"
name="selectedClientId" id="selectedClientId"
headerKey="-1" headerValue="Client List"
onchange="onChangeSelect()"
/>
III. The select's textfield:
Filter:<s:textfield name="filterClient" id="filterClient" size="15" autocomplete="off"/>
IV. The onChangeSelect():
function onChangeSelect() {
document.getElementById('deviceListForm').action = '<s:url value="/admin/displayDeviceListPage.action"/>';
document.getElementById('deviceListForm').submit();
}
In the image: in the first select is how looks the selected option after jquery filter and in the other 2 selects are "the good" selected options.
http://i.stack.imgur.com/TAJeY.png
EDIT: So, after the first response to this post (Thanks Amit1992) I started digging further. In Mozilla after the first click (after the frame or dotted line appears) a request is made to the server with the old selected item (or null if none selected), the page refreshes as nothing happened.
In Chrome, on the other hand, the first click does not make any request. It just selects (let's say) the select tag. And the second select makes a good request.
Short story:
mozilla: click 1 -> request with old selected value ->refresh -> no changes
chrome: click 1 -> selects the select tag and no request is made -> click 2 -> request as it should happen
IE - works ok. 1 click-> select and load page as it should . OK this really surprises me. at first I thought is useless to look in IE what happens.
EDIT2
After some digging i concluded that the problem is that when typing in the textfield the select loses focus. If I put $('#selectedClientId').focus();
in the filterByText function at the end of the $(textbox).bind('change keyup', function() the fist select is focused after every char written. But this gives me another problem. I can't write more than 1 char at a time. I have to click the textfield, write a char, click again, write a char etc.
May be this will help you. i did some modification in your code.
$(function() {
$('#selectedClientId').filterByText($('#textbox'), false);
$("#selectedClientId").change(function(){
alert("you have selected ++ " + $(this).val());
});
});
I used change() event of jquery instead of javascript onChange().
you can refer this link http://jsfiddle.net/amitv1093/q55k97yc/ and I recommend you to use jquery fully if you are using it.
kindly let me know if it will work.
I solved the problem by changing the whole filter function. The function with problem was taken from a stack overflow question response (How to dynamic filter options of <select > with jQuery?). The problem is, from what I concluded, that the $(textbox).bind('change keyup', function() line was changing the focus on the textfield, so the first click was changing the focus to the select tag. The new function, the one that works was taken from the same post, John Magnolia's answer:
$(document).ready(function() {
filterClient();
filterLocation(); //same as filterClient
filterViewpoint(); //same as filterClient
});
function filterClient(){
var $this, filter,
$input = $('#filterClient'),
$options = $('#selectedClientId').find('option');
$input.keyup(function(){
filter = $(this).val();
$options.each(function(){
$this = $(this);
$this.removeAttr('selected');
if ($this.text().toLowerCase().indexOf(filter.toLowerCase()) != -1) {
$this.show();
} else {
$this.hide();
}
});
});
}

Search value in div

I've got a little function which allows to search values through rows, but there is a problem with it - search function is not working properly.
Please take a look at the fiddle here http://jsfiddle.net/4f3WF/
Try to set text in input to "798" for example.
In the end this function must be able to search through entire row, not just only first or last ms-column div. I just don't get what's wrong.
Just try with:
e.find('.multiple-selector-table .ms-search-label .ms-search').on("keyup", function() {
var value = $(this).val();
e.find('.multiple-selector-table-row').hide();
e.find('.ms-column:contains("' + value + '")').parents('.multiple-selector-table-row').show();
});
Updated fiddle
In the first step, we hide all rows. Next we search for cells that contain value passed in input and show their parent rows.

option:selected not triggering .change()

I have a dropdown box that has a list of institutions in it. Now if I manually select an option, it works and I am able to grab the correct value.
However, I have a select rates button which uses JavaScript to pull up a rate sheet. You select a rate from that sheet and it will select an option from the dropdown for you (one that corresponds with the rate from the rate sheet). If I use this method, it doesn't trigger a .change() therefor I can't get a value for the selected option.
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").text()
$("fi").text(value);
});
Any suggestions? I have tried .change() and .click() but nothing.
Once you are in the change function you don't have to do another search or selector because you already have the object you just have to find the selected option from it. So you can try this:
$('#id_financial_institution').change(function () {
var value = $(this).find("option:selected").text();
$("fi").text(value);
});
If the code still doesn't return you answer start to add alerts at each point to see where you are and what values you have and work your way from there?
Rather than .text() use .val()
$(function() {
$('#id_financial_institution').change(function () {
var value = $("#id_financial_institution option:selected").val()
alert(value);
});
})
Here is a sample demo, without your html. I am just alerting the value.
DEMO
You're going about this all wrong. You already have the select element in this, all you need is the value of that select element.
$('#id_financial_institution').change(function () {
var value = $(this).val();
$('#fi').text(value); //i assume `fi` is an [id]
//do more stuff
});
I went inside my AJAX call and got the value of the fields I needed there. For some reason, when using the AJAX call, it wouldn't fire the .change() on that particular field.
Thanks for all your input everyone.

Problem adding and removing in array with jquery and checkboxes

I got a problem when I try to create an array of checked checkboxes.
The checkboxes are generated dynamically with an "onChange" attribute that calls the javascript function to add or remove in the array. The function gets "talla" that it is the value to add or remove.
This is my javascript code for the function: (arrayTallas is global)
function checkbox_marcado(talla)
{
if(jQuery('#id_talla').is(':checked') == true)
{
arrayTallas.push(talla);
}
else //elimina posicion del array al deseleccionar un checkbox
{
var index = arrayTallas.indexOf(talla);
arrayTallas.splice(index,1);
}
}
The problem is that the first checkbox work fine, but the others are not deleted.
For example. If a have 3 checkboxes with values "1" "2" "3" if I click on the first one, it is added normally, and if I click again on it, it is deleted normally too... but if I click on the first one, and then on the second one, when I click again on the second one to delete it from the array, when I print the array this is what I get: 1 2 2
Thanks
If you're using jQuery anyway, why not use a function like this:
$('#tallas').live('click', function(){
$(':checkbox:checked').map(function() {
return this.value;
}).get().join(',');
});
I think you mean to say:
jQuery('#id_' + talla)
where you're saying:
jQuery('#id_talla')
Also check to make sure you don't have multiple checkboxes with the same id attribute.

Categories