Form not reading the select attribute when added option via ajax - javascript

I am prepending an <option> via ajax like this:
success: function(data) {
jQuery('#usp-cat-combo-1').prepend('<option selected="selected" value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
The thing is when I submit the form, that option says not selected and I need to manually select it, even tho I have given the attribute selectedwhen I added it

Try setting value of the <select> instead of setting selected attribute on the option
jQuery('#usp-cat-combo-1')
.prepend('<option value="'+data.cat_id+'">'+data.cat_name+'</option>');
.val(data.cat_id)
Note this assumes the <select> is not a multiple. If it is a multiple can set prop('selected',true) on the new first child

What you have to do:
Defined the option which you want to select by default like:
var selected;
success: function(data) {
data.cat_id=='1' ? selected = 'selected="selected"' : selected = '';
jQuery('#usp-cat-combo-1').prepend('<option '+selected+' value="'+data.cat_id+'">'+data.cat_name+'</option>');
}
Now it just add Selected Attribute at one option that you defined not every option.
Note :
Assume that you have data as an array.
You can use data.cat_name or other as you want instead of cat_id to defined your Selected Option.
Feel free to comment for more help or other simplification :)

Related

Select element returning value only when disabled

I have a select box as follows:
<select id="selectbox" class='info-entry-select' name="country">
<option value="1" selected="selected">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
This select box is in a hidden div that, when appearing, refreshes the select box options using ajax and a separate php file. Here's the javascript that updates the select box:
$("#changeselectoptions").on('click', function() {
$.ajax({
type: "GET",
url: "includes/selectoptions.php",
dataType: 'json',
success: function(result){
// Replace options of select box
var $el = $("#selectbox");
var newOptions = result['catsOrderList'];
// newOptions correctly returns an array in the form of {1: "One", 2: "Two", 3: "Three", 4: "Four"}
$el.empty(); // remove existing options
$.each(newOptions, function(key,value) {
$el.append($("<option></option>").attr("value", key).text(value));
});
}
});
return false;
});
If I now call: $('#selectbox').val(); I get undefined and I'm not sure why? To make matters more confusing, if I disable #selectbox (using a toggle switch that adds .attr('disabled', 'disabled'); to #selectbox, then try $('#selectbox').val(); I get the expected val of 1, 2, 3, etc.
How can I get this value without disabling the box, or what have I overlooked?
Edit:
I've been asked where my $('#selectbox').val(); call is. It's not any more involved than I mentioned above, but to be thorough, it's called from a submit button in the same div as the select element as follows:
$("#submitbutton").on('click', function() {
var selectBoxVal = $('#selectbox').val();
console.log('value is: ' + selectBoxVal);
return false;
});
My only idea so far is that it may be a dom issue? I say that ignorantly as my knowledge doesn't quite know the full ins and outs but I've seen issues where elements are altered live by javascript and not retrieved correctly by later javascript calls - whereas they work fine if the elements being retrieved existed when the page loaded.
I don't assign a selected property to any of the options but I don't believe this should cause undefined to be returned. For example, if I disable the select box, the value is returned correctly from the same query (as mentioned above) yet it still doesn't have a selected property added manually. I digress, but is it required to add a selected property when creating a series of options in javascript? Which option is initially presented as selected is irrelevant to me from a usage point of view but I'd be happy to follow best procedures. I assumed that the browser interpreted the displayed option as selected if none were marked as such.
I believe that the "value" of the select will be the <option> that has the attribute "selected" within that selectbox. Otherwise, there is no indicated value for that input.

Selection from dropdownlist javascript event

I have this html part code :
<p><label>Taxe </label>
<select id="id_taxe" name="id_taxe" style="width: 100px;" onchange="taxselection(this);"></select>
<input id="taxe" name="taxe" class="fiche" width="150px" readonly="readonly" />%
</p>
Javascript method :
function taxselection(cat)
{
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
I'd like to set the value of taxe input to the selected value from the dropdownlist.It works fine only where the dropdownlist contains more than one element.
I try onselect instead of onchange but I get the same problem.
So How can I fix this issue when the list contains only one element?
This works:
$('#id_taxe').change(function(){
var thisVal = $(this).val();
var curVal = $('#taxe').val();
if(thisVal != curVal)
$('#taxe').val(thisVal);
$('#select option:selected').removeAttr('selected');
$(this).attr('selected','selected');
});
Use the change method which is very efficient for select boxes. Simply check the item selected isn't currently selected then if not, set the value of the input to the selected value. Lastly you want to remove any option's attr's that are "selected=selected" and set the current one to selected.
Just include this inside a $(document).ready() wrapper at the end of your HTML and the change event will be anchored to the select field.
Hope this helps.
http://jsbin.com/populo
Either always give an empty option, or in your code that outputs the select, check the amount of options, and set the input value straight away if there's only 1 option.
A select with just 1 option has no events, since the option will be selected by default, so there's no changes, and no events.
As DrunkWolf mentioned add an empty option always or you can try onblur or onclick event instead, depending on what you are actually trying to do.
Ok, just to stay close to your code, do it like this: http://jsfiddle.net/z2uao1un/1/
function taxselection(cat) {
var tax = cat.value;
alert(tax);
$("#taxe").val(tax);
}
taxselection(document.getElementById('id_taxe'));
This will call the function onload and get value of the element. You can additionally add an onchange eventhandler to the element. I highly recommend not doing that in the HTML! Good luck.

outerHTML and attribute updates

I'm trying to get the HTML code as a string with the attribute updates.
I've a select tag, whose options I update using JavaScript.
By default, a first option is selected using the HTML attribute selected="selected".
If I unset selected from the first option using option1.selected = false and set option2.selected = true for the second option, and then call the outerHTML of a select, I get
<select>
<option selected="selected">one</option>
<option>two</option>
<option>three</option>
</select>
As you can see, selected attribute is still on the first option, while it has been moved to the second option. The expected result is
<select>
<option>one</option>
<option selected="selected">two</option>
<option>three</option>
</select>
Here's an example http://jsbin.com/adAbAMe/2/edit?html,js,console,output (click run with js to get a result) which shows, that if a selected attribute has been changed, it doesn't change in the HTML code.
But I need to get the final HTML from outerHTML with the successful attribute updates, because if I move this select somewhere I won't get any updates I've made before using JavaScript.
Is there any method to get the HTML as a string with the real attributes values?
The selected attribute isn't automatically updated, but you can set it to be removed and added to the proper elements.
//remove "selected" from first
if (i==0) {
option.selected = false;
option.removeAttribute("selected");
}
//add "selected" to second
if (i==1) {
option.selected = true;
option.setAttribute("selected", "selected");
}
Here's a working fiddle.
You can use
option.setAttribute('selected', 'selected');
and
option.removeAttribute('selected');
Try
$('button').click(function () {
console.log($('select').prop('outerHTML'))
})
$('select').change(function(){
$(this).find('option[selected]').removeAttr('selected');
$(this).find('option:selected').attr('selected', 'selected');
})
Demo: Fiddle
From the DOM Specification:
selected of type boolean
Represents the current state of the corresponding form control, in an interactive user agent. Changing this attribute changes the state of the form control, but does not change the value of the HTML selected attribute of the element.
(emphasis mine)
To get the effect you're looking for, you want option.setAttribute('selected', 'selected'), though you'll also need option.removeAtrribute('selected') on the other options.

unexpected behaviour in option tag in HTML

I have the following code
<select id="part">
<option>noun</option>
<option>verb</option>
<option>adjective</option>
</select>
In the above code, I don't have any value attribute each option tag.
there is only text node.
when I access the option tag
$("#part").val(); I get what is selected in dropdown box. ie, "noun"
but when I access $("#part").text(), there is empty string.
but when I create, option tags dynamically in jquery for
<select id="part"></select>
using
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
Here the value is attribute is needed to get the option selected.
without value attribute, $("#part") is undefined.
can somebody explain the discrepancy here? of if my understanding is not correct. Thanks
Check here DEMO http://jsfiddle.net/yeyene/yH4Fb/
You need to get only the selected option text coz there are three options,
when you get $("#part").val(); you directly get the selected value (only one selected value). But when you get $("#part").text().. you are getting the text of the whole select text where you have three options and three types of text.
JQUERY
$(document).ready(function(){
var names=["noun","adjective","verb"];
for (var i =0;i<names.length;i++) {
var option=$("<option>",{
value:names[i],
text:names[i]});
$("#part").append(option);
}
$("#part").on('change', function() {
alert('Value is '+$(this).val());
var text = $("#part option:selected").text();
alert('Text is '+text);
});
});
$("#part").text() doesn't return nothing but it won't return what you expect (see this fiddle).
Explanation: text returns the text of the object strips out the html (see jQuery docs examples), so what you will be getting is the inner contents of the select after the html was stripped out.
If you want the text of the selected value, include the selected option in your jquery selector: i.e. $('#part option:selected').text() which uses the jQuery psuedo-selector (also in my fiddle).

How to change data on select option dropdown

need a small help to change data from option selected.
The data is populated first to the dropdown option list from a JSON result, in the same JSON is the second data thta need to be changed on select the option from dropdown.
What i want os to change the price on select the store.
This is my javascript code:
$(function() {
var pricestore = [{"product_id":"1","store_id":"1","price":"120.00","sequence":"0","id":"1","parent_id":"0","name":"Store 1","email":"store1#store1.com"},{"product_id":"1","store_id":"2","price":"140.00","sequence":"0","id":"2","parent_id":"0","name":"Store 2","email":"store2#store2.com"}];
$.each(pricestore, function(i, option) {
$('#sel').append($('<option/>').attr("value", option.id).text(option.name));
}),
//Trying to populate the price on div id
$$('#price-store').each(function(el) {
el.innerHTML = pricestore;
});
})
This is the HTML to get the data
<select id="sel"></select>
<div id="price-store"></div>
Here is also an example on jsfiddle
http://jsfiddle.net/A386B
Any help is appreciated.
Check this:-
Demo
As per what i understood from your question you need to show the price in the div as the dropdown values are changed. You can use below method. You need to use use a change event on the dropdown.
This approach uses Index() of the option element selected and retrieves the corresponding record from JSON.
$('#sel').change(function () {
$('#price-store').text(
pricestore[$('option:selected', this).index()].price);
});
Another way is to use data-attributes on the option element to store the respective price and retrieve it on change of dropdown value.
Demo
$('#sel').append($('<option>',
{
"value" :option.id,
"data-price" :option.price
}).text(option.name));
}),
$('#sel').change(function () {
$('#price-store').text($('option:selected', this).data('price'));
});
You use $$ to select your div instead of $. $('#price-store')
The second parameter of the function passed to the .each() method is the element not the first. function(i, el) {
Why are you using .each() for one div?
You'll have to format the data in pricestore to display it in a div, otherwise all you'll get is [Object object],[Object object].
Or this one:
<div id="price-store"></div
<form>
<select id="price">
<option>120</option>
<option>140</option>
<option>160</option>
</select>
</form>
and:
$('#price').change(function() {
$('#price-store').text($('#price').find(":selected").text());
});
http://jsfiddle.net/XcSZL/8/

Categories

Resources