Ok this might be a bit confusing, but here goes. Let's say I have a a few select dropdowns on a page.
<select id="filter" name="filter[]">
<option value="">-- Select Filter --</option>
</select>
<select id="load_choice" name="load_choice[]">
<option value="">-- Select Load_choice --</option>
</select>
<select id="plastic" name="plastic[]">
<option value="">-- Select Plastic --</option>
</select>
These are dynamically filled from a database with an ajax request. Each set of select options are dependent on the previous selection. This is just a snippet of all the select dropdowns, but essentially their selections creates a "product". Here is the javascript that connects to the php (which connects to the DB).
$(document).ready(function() {
$('#filter').change(function(){
$('#load_choice').fadeOut();
$('#loader').show();
$.post("ajax/ajax_load_choice.php", {
country: $('#country').val(),
filter: $('#filter').val()
}, function(response){
setTimeout("finishAjax('load_choice', '"+escape(response)+"')", 400);
});
return false;
});
$('#load_choice').change(function(){
$('#plastic').fadeOut();
$('#loader').show();
$.post("ajax/ajax_plastic.php", {
country: $('#country').val(),
filter: $('#filter').val(),
load_choice: $('#load_choice').val()
}, function(response){
setTimeout("finishAjax('plastic', '"+escape(response)+"')", 400);
});
return false;
});
$('#plastic').change(function(){
$('#UG_tipping').fadeOut();
$('#loader').show();
$.post("ajax/ajax_UG.php", {
country: $('#country').val(),
filter: $('#filter').val(),
load_choice: $('#load_choice').val(),
plastic: $('#plastic').val()
}, function(response){
setTimeout("finishAjax('UG_tipping', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#loader').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
}
NOW, let's say I want to add another of the exact same form with the exact same select options in order to "create another product" on the same page (hence the array on the NAME tag for each select). Since the form is dependent on unique IDs, how could I make the IDs in this chunk of code dynamic?
$('#filter').change(function(){
$('#load_choice').fadeOut();
$('#loader').show();
$.post("ajax/ajax_load_choice.php", {
country: $('#country').val(),
filter: $('#filter').val()
}, function(response){
setTimeout("finishAjax('load_choice', '"+escape(response)+"')", 400);
});
return false;
});
I will eventually have 5 sets of those select groups so the user can create 5 products. How would I make it so I don't have to do id="filter1" and id="filter2" to coincide with $('#filter').change(function....blah blah blah. Basically, can I make ID's in a jquery function dynamic?
It is recommended to have unique ids always.
The main reason is that performing a selector like $('#myId') may give unpredictable results when there are multiple elements in the page with that id.
jQuery relies on the native browser implementation of document.getElementById(), which in most cases returns just the first element found.
If you want to make sure by using jQuery that you have unique id's you can do something like:
$('select[id=filter]').each(function(i,el){
el.id=el.id+'-'+i;
});
If you already have unique id's you can use a prefix selector(^= or |=) like this:
$('select[id^=filter]');
//or
$('select[id|=filter]');
You can see a live example of both in this jsFiddle
Alternately, if you don't care about duplicate ids you can select all elements with a given id (including duplicates) like this:
$('[id=my-id]');
I'm not, really, sure what you're asking. My best guess is something along the lines of:
Using jQuery, can I increment the id fields of the form elements in order that I can add multiple forms to the page, and have each form uniquely identified?
If this is a reasonable understanding of your question, and looking at #Baylor Rae's answer (which is definitely a valid interpretation) I'm not necessarily right, then the following should work:
jQuery
$(document).ready(
function(){
$('#formAdd').click(
function(){
var count = $('#formsBox form').length;
$('#formsBox form').eq(0).clone().appendTo('#formsBox').find('label, input').each(
function(){
if (this.id) {
var curId = this.id;
$(this).attr('id',curId + count);
}
else if ($(this).attr('for')) {
var curFor = $(this).attr('for');
$(this).attr('for', curFor + count);
}
}
);
}
);
}
);
html
<div id="formsBox">
<form action="" method="post">
<fieldset>
<ul>
<li>
<label for="firstInput">First Input:</label>
<input type="text" name="firstInput" id="firstInput" />
</li>
<li>
<label for="secondInput">SecondInput:</label>
<input type="text" name="secondInput" id="secondInput" />
</li>
</ul>
</fieldset>
</form>
</div>
<div id="formAdd">Add another form</div>
Effectively, on clicking the #formAdd div the jQuery finds the form, works out how many there are and stores that as the variable count.
It then clones the first form (without the .eq(0) the first click clones one form, the second click clones two forms and it's exponential thereafter), appends it to the same container (#formsBox, for want of a better name) and then looks for the labels and inputs; if these have an id (input) or a for (label) attribute, it adds the previously-stored count variable to these attributes, uniquely identifying them.
This is a pretty poor explanation, and I'm sure there's a far prettier way of achieving the same end-result in the jQuery, but it does seem to work. There's a JS Fiddle demo here
This is what I came up with, wrap each set of select boxes in a div or something. And then remove their id attribute.
With jQuery you can bind a change and still grab the other two selects like this.
$('select[name=filter[]]').change(function() {
var $parent = $(this).parent();
// hide and show other selects
$parent.find('select[name=load_choice[]]').fadeOut();
$parent.find('select[name=plastic[]]').show();
// make the ajax call
});
// repeat the above code for the others
Related
I am having a custom table that has several items and has a column of status. I have created a dropdown using select for changing the status.
Here, what I want to do is, on change of the status select option, the value of status of that particular row should be updated in the db.
I am able to get the value of the select using jquery but I am not sure how to update the table when multiple dropdowns are being selected together.
I am having the below select options,
<select id ="update-statusDropDown">
<option name="waiting" value="waiting">Waiting</option>
<option name="due" value="due">Due Diligence</option>
<option name="escrow" value="escrow">Escrow</option>
<option name="inspection" value="inspection">Inspection</option>
<option name="closed" value="closed">Closed</option>
</select>
My jQuery is something like below,
jQuery(document).ready(function () {
jQuery('select#update-statusDropDown').change(function () {
//Selected value
var inputValue = $(this).val();
alert("value in js " + inputValue);
//Ajax for calling php function
jQuery.post('update-listing-status.php', {dropdownValue: inputValue}, function (data) {
alert('ajax completed. Response: ' + data);
//do after submission operation in DOM
});
});
});
I want to update status value in the table as per the 'inputValue' from the dropdown. Also, if multiple dropdowns are selected together, how can I update all the values together.
Please can anyone help?
The screenshot of my current table is attached.
You have registered the change event of the select using the ID of that drop down which means only the drop down with that ID will trigger the request you making via the jquery.post
instead use class attribute for the select elements and register the change event on that class
now to get the unique element you can use the data attribute of that select element and option for example data-tableid="something"
in this case you can register all change event of all select elements and be able to extract the values that is only unique to the given table or column name.
$('.class-name').on( 'change' , function(){
// Get the Select itself
var me = $(this);
var tableid = me.data('tableid');
var something = $(this).find(':selected').data('something');
console.log( tableid );
console.log( something );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="class-name" data-tableid="table-id">
<option value="the value" data-something="some value 2">The Title 2 </option>
<option value="the value" data-something="some value">The Title</option>
</select>
So now since you have the ability to uniquely identify which select is being used and which option is being used you can make the request as you wish.
In my cart i have my products added, there are stored in sessions.
I want to store my selected option from all dropdown when the page is refreshed.
I need to refresh my page so my sessions can be updated so i can post in my database all the updated values.
What is wrong...
if i select an option for the first row of my product it saves in local storage.but when i select another product option from other row,it overwrites the local storage,so my local storage is saving only one option,and when selected other option from other products it is rewriting my only one save option in local storage.i have to save multiple option.
Without refresh what happens is...
lets say that i've selected 1 cushion in my gallery.
So in my cart this cushion will be 1 product, and if i add two more by clicking plus button and then click on confirm order,it will post in my DB the value of 1.
But not 3.
So my page needs to refresh, so for that i need to save all dropdown selection so i can refresh the page.
So far i tried to save it,but it saves the first row of my cart.
This is what i tried...
$(function() {
if (localStorage.getItem('fabric')) {
$(".fabric option").eq(localStorage.getItem('fabric')).prop('selected', true);
}
$(".fabric").on('change', function() {
localStorage.setItem('fabric', $('option:selected', this).index());
});
});
$(function() {
if (localStorage.getItem('size')) {
$(".size option").eq(localStorage.getItem('size')).prop('selected', true);
}
$(".size").on('change', function() {
localStorage.setItem('size', $('option:selected', this).index());
});
});
this is my foreach loop if needed to understand it better.
this script below is not important for this question,but it shows how i am handling my dropdowns to make ajax get values based on dropdown selection using data attribute.
script that gets cost and subtotal
Ok... Took a liitle time, but you will like my solution (I think).
We have to set storage row by row...
So an .each() loop has to be done on product rows.
We use the index of the .each() as a part of the storage name to ensure no overwriting.
Given this HTML that I made just for this example:
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
<div class="row">
<!-- other elements like img etc... -->
<select class="fabric">
<option>jeans</option>
<option>leather</option>
<option>cotton</option>
</select>
<select class="size">
<option>small</option>
<option>medium</option>
<option>large</option>
</select>
</div>
Here is the script:
$(function() {
$(".row").each(function(index){
// Fabric selection
if (localStorage.getItem('row_'+index+'_fabric')) {
$(this).find('.fabric option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_fabric')).prop('selected', true);
console.log("Row#"+index+" get-fabric: "+localStorage.getItem('row_'+index+'_fabric'));
}
$(this).find(".fabric").on('change', function() {
localStorage.setItem('row_'+index+'_fabric', $(this).find('option:selected').index());
console.log("Row#"+index+" set-fabric: "+$(this).find('option:selected').index());
});
// Size selection
if (localStorage.getItem('row_'+index+'_size')) {
$(this).find('.size option').prop('selected', false).eq(localStorage.getItem('row_'+index+'_size')).prop('selected', true);
console.log("Row#"+index+" get-size: "+localStorage.getItem('row_'+index+'_size'));
}
$(this).find(".size").on('change', function() {
localStorage.setItem('row_'+index+'_size', $(this).find('option:selected').index());
console.log("Row#"+index+" set size: "+$(this).find('option:selected').index());
});
});
});
Try it on this CodePen!
(Change the selects and hit "Run" to refresh)
I am dynamically generating two paragraphs and two input fields inside a div. There may be numerous divs generated, depending upon the number of records pulled from the database. Each para and input field is assigned a unique id.
When the user clicks on a field, say firstText_id, jQuery hides the field and shows an input field firstText_input_id in its place. The user updates the input field, and on clicking away, an ajax script is called to update the database and return a success message.
My problem is that, when the user clicks on one field in any record, and updates it, then clicks away, the ajax calls for both fields are made.
PHP
echo "<div class=\"single seven columns boxTable2 \" id=\"{$vid}\">
<div class=\"seven columns alpha omega\" >
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega firstHead\">First name: </p>
<p class=\"firstText single two columns alpha omega\" id=\"firstText_{$vid}\"
data-vid=\"{$vid}\">{$first}</p>
<input type=\"text\" id=\"firstText_input_{$vid}\"
class=\"firstText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$first}\"/>
</div>
<div class=\"four columns alpha omega\" >
<p class=\"single two columns alpha omega lastHead\" >Last name: </p>
<p class=\"lastText single two columns alpha omega\" id=\"lastText_{$vid}\"
data-vid=\"{$vid}\">{$last}</p>
<input type=\"text\" id=\"lastText_input_{$vid}\"
class=\"lastText_input single two columns\"
data-vid=\"{$vid}\" value=\"{$last}\"/>
</div>
</div>
</div>
jquery
jQuery.noConflict();
jQuery(document).ready(function($){
var vidID = '';
$(document).on('click', '.firstText', function ()
{
vidID=$(this).data('vid');
$('#firstText_'+vidID).hide();
$('#firstText_input_'+vidID).show();
}).change(function()
{
var newFirstText=$('#firstText_input_'+vidID).val();
var firstTextDataString = 'vid='+ vidID +'&first='+newFirstText;
if(newFirstText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: firstTextDataString,
cache: false,
success: function(html)
{
$('#firstText_'+vidID).html(newFirstText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$('.firstText_input').mouseup(function(e)
{
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// return false; //(does the same as the above 3 functions)
});
// Click away action
$(document).mouseup(function()
{
$('.firstText_input').hide();
$('.firstText').show();
});
$(document).on('click', '.lastText', function ()
{
vidID=$(this).data('vid');
$('#lastText_'+vidID).hide();
$('#lastText_input_'+vidID).show();
}).change(function()
{
var newLastText=$('#lastText_input_'+vidID).val();
var lastTextDataString = 'vid='+ vidID +'&last='+newLastText;
if(newLastText.length>0)
{
$.ajax({
type: "POST",
url: "/go/to/php.php",
data: lastTextDataString,
cache: false,
success: function(html)
{
$('#lastText_'+vidID).html(newLastText);
}
});
} else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".lastText_input").mouseup(function()
{
return false;
});
// Click away action
$(document).mouseup(function()
{
$(".lastText_input").hide();
$(".lastText").show();
});
});
As the unique IDs are generated dynamically from the database records, I can’t find a way of associating the user’s click to the field being updated without the other field in the record being updated. I’m a relative beginner with jQuery/javascript. How can I isolate the user’s action to the field being clicked? I have tried click selectors like ‘[id^=”firstText_input_”]’. Probably a simple error, but I have been round it too many times to see the error.
The event that causes the ajax to happen is actually bound to the document, therefore, anytime ANY input changes, the document receives the event and performs the ajax request.
See below:
$(document).on('click', '.someclass', function () {...}).change(function () {...});
.change is targeting $(document), not $('.someclass'), you'll have to use the same delegation syntax as before to instead delegate it to the target element.
$(document).on('click', '.someclass', function () {...}).on('change', '.someclass', function () {...});
both firstText and lastText are affected by this issue, which is why both trigger any time you change either input.
Additionally... your event binding is very inconsistent. In some cases you're using delegation, and in others you are not. Since you're replacing the entire content of the div, you should be using event delegation for all of the events within that div.
I'm trying to populate Cities as per the State selected by user in dropdown lists.
I've a function in jquery defined as:
function onchange1(dropdownmenu,field_name,id)
{
alert(field_name);
$.post(
'wppb.city.php',
{ field_name: id},
function(data) {
alert(data);
$('#'+dropdownname).html(data);
alert("Data Loaded: " + data);
});
alert($('#'+dropdownname).html());
}
and I'm trying to get values from the location where I've called this function.
I've called this function in html tags as:
<select name="state" id=state onChange="onchange1(city,state,this.value);">
where city is the name of my 2nd dropdownmenu, state is the field_name and this.value is the id.
But when this function is being called and when alerted it's showing [objectHTMLSelectElement].
How to retrieve values from HTML and use it in jquery function ?
I believe what you want is
$('#'+field_name.id).val()
You might also want to look into serializeObject , a good post is this Convert form data to JavaScript object with jQuery
I am using jquery star rating plugin "Raty" https://github.com/wbotelhos/raty.
i am generating a result set from database with PHP. that includes score also. I want set score property for every individual rating component. how can I do that?
I am using this syntax for showing the stars.
$('.stars_small').raty({
readOnly : true,
half : true,
score : 2,
space : false
});
<div class="stars_small"></div>
there are many div in a single page with the class "stars_small" generated dynamically. I want to set "score" for every div.
$('.stars_small').raty({
readOnly : true,
half : true,
score: function() {
return $(this).attr('data-rating');
}
space : false
});
this worked fine for me.
the plugin is adding a hidden textbox in every div with class="stars_small"
like this
<div class="stars_small">
<input type="hidden" name="score" value="3.5" readonly="readonly">
</div>
So I just set the value attribute with number coming from database query.
Try this
$('.stars_small').each(function() {
$(this).raty({
readOnly : true,
half : true,
score : 2,
space : false
});
});
Assuming that you have generated with PHP the JS lines:
// lines of JS generated with a loop in PHP (for the rate content)
var rates = [];
rates.push({...one rate coming from PHP...});
rates.push({...one rate coming from PHP...});
// etc...
You can run you rating star with :
$(document).ready(function() {
$(".starts_small").each(function(index, element) {
$(this).raty(rates[index]);
});
});
Here is what i did:
I created a separate class for each of those star divs:
<div class="star s0"></div>
<div class="star s1"></div>
<div class="star s2"></div>
I also generate the array of values in my template (that is, pass the values from my server-side script to the web page). Like so:
var array = new Array(2.4, 2.9, 5.0);
And then I declare the thing common for all the three "star banners" in the $(".star") call, and set the values in a cycle:
$('.star').raty({
half : true
});
for (i = 0; i < array.length; i++) {
$('.s' + i).raty({
score:array[i]
});
}
For V.2.7 Jquery raty is the form:
If you need to start you score depending of a dynamic value, you can to use callback for it.
You can pass any value for it, not necessarily a data- value. You can use a field value for example.
<div data-score="1"></div>
$('div').raty({
score: function() {
return $(this).attr('data-score');
}
});