In my code, I empty a <select> element and rebuild it again with available times.
However I am trying to set the <option> to selected if it matches the previously selected time:
if(time == currenttime) {
console.log("Matched Time "+currenttime);
$("#time-start").append($("<option></option>").attr("value", time).text(time)).prop("selected","selected");
} else {
$("#time-start").append($("<option></option>").attr("value", time).text(time));
}
I get the console message Matched Time but the .prop("selected","selected") isn't setting the newly created option to be selected.
How can I set it to be selected?
I think your code will get more readable like this (and thus makes it easier to set the selected property at the right place):
let $opt = $("<option></option>").attr("value", time).text(time);
if(time == currenttime) {
console.log("Matched Time "+currenttime);
$opt.prop("selected","selected");
}
$("#time-start").append($opt);
You were close, set selected with option element
var option = $("<option>", {"selected" : time == currenttime, text: time, value: time });
$("#time-start").append(option );
OR, Use .val()
$("#time-start").val(time)
Change it to following:
$("#time-start").append($("<option></option>").prop("selected",true).attr("value", time).text(time));
Related
I'm trying to add and remove a div depending on the value of a select menu. This code works well a first: when the value of the select is 2 div appears. When I return to the first value (1), the div disappears. However if I select the value 2 again, the div is not add again. Any idea ?
<select id="interv_base_youorthird" name="interv_base[youorthird]" class="form-control">
<option value="1">Pour moi</option>
<option value="2">Pour un tiers</option>
</select>
<input type="hidden" id="extra-counter" value="0">
$("#interv_base_youorthird").change(function(){
if( $(this).val() == "2" ){
const index = +$('#extra-counter').val();
const tmpl = 'hello world';
//Add sub form
$('#interv_base_intervExtras').append(tmpl);
$('#extra-counter').val(index + 1);
}
else{
$('#interv_base_intervExtras').remove();
}
});
The problem is because you remove() the #interv_base_intervExtras element when you select the first option again. When you move back to the second option #interv_base_intervExtras no longer exists in order to read the data-prototype attribute from it.
To fix this use empty(), instead of remove(), to clear the content of the element instead of removing the entire element:
var $interv = $('#interv_base_intervExtras');
$("#interv_base_youorthird").change(function(){
if ($(this).val() === "2") {
const index = parseInt($('#extra-counter').val(), 10);
const tmpl = $interv.data('prototype').replace(/__name__/g, index);
$('#interv_base_intervExtras').append(tmpl);
$('#extra-counter').val(index + 1);
} else {
$('#interv_base_intervExtras').empty(); // <-- amend this
}
});
Note that I amended the logic slightly in the above example to cache the #interv_base_intervExtras element and to explicitly use parseInt() instead of coercing the string to an int using the + operator.
I'm running into a little trouble trying to determine the value of an HTML select object.
I've got 2 items, which I'm putting down as Value 1 or Value 2, however any method I try just returns "Undefined" when printed to console
var catId = document.getElementById('catid');
var catCheck = catId.options[catId.selectedIndex].value;
console.log(catId);
console.log(catCheck);
<select name="catid" id="catid">
<option value="1">Category</option>
<option value="2">Product</option>
</select>
However when I console.log(catId.Value) or console.log(catCheck.value) (I'm obviously not trying both at the same time) I just returned an "Undefined" value.
I want to run an IF ELSE statement based on this variable, so ideally I'd like it to be able to pick up at least one of the two values!
Likelihood is I've made a dumb mistake and just can't see the wood for the trees but any help would be appreciated
You could also get the selected <select> <option> like this:
var catCheck = document.getElementById("catid").selectedIndex;
console.log(catCheck);
Your first option would return 0, your second 1 and so on.
You wouldnt have to use value this way.
You can listen for the select element to change by adding an event listener for the change event. This will trigger the performDropdownAction function anytime you select a new value within the dropdown list. You can then use this.value to get the value of the current drop-down item you're on.
Also, I've added a window.onload event, which will fire when your webpage has loaded, meaning it will perform the performnDropdownAction when the page loads and when a new item is selected.
See working example below :
const performDropdownAction = function() {
let current = this.value || document.getElementById('catid').value;
if (current == 1) {
console.log("One is selected");
} else if (current == 2) {
console.log("Two is selected");
}
}
window.onload = performDropdownAction;
document.getElementById('catid').addEventListener('change', performDropdownAction);
<select name="catid" id="catid">
<option value="1">Category</option>
<option value="2">Product</option>
</select>
I have a <select>, and on button click users can select the next option:
$(".someButton").on('click', function () {
var $opt = $("select :selected");
$("select").val($opt.next().val());
});
The problem is that on the last option, $opt.next().val() returns some unselectable value, and apparently jQuery selects the first option by default. What I would like is for it to stay on the last option.
Is there any way to do this (preferably without checking the position of $opt or the length of $opt.next())?
Here's a more efficient way to do it:
$(".someButton").on('click', function () {
var el = $("select")[0];
el.selectedIndex = Math.min(el.selectedIndex + 1, el.length - 1);
});
If you want to stick to jQuery, set the option to selected:
$opt.next().prop('selected', true);
If $opt is the last one, .next() will return an empty set, so nothing will change.
I would just handle the case to be honest. It would be simple to add the following:
if(!$opt.is(':last-child')) {
$("select").val($opt.next().val());
}
I'm trying to do a simple script that checks a date and if "day chosen" == "tomorrow" then change a dropdown containing delivery options:
Drop down:
0-When?(selected)
1-AM
2-PM
If day = tomorrow then I remove in javascript the options:
Drop down:
0-When?
2-PM(selected)
The script:
// remove all options first
document.getElementById('inputheurelivraison').options.length = 0;
if (parseInt(datebits[2]) == parseInt(demain)){//remove am
document.getElementById('inputheurelivraison').options[0] = new Option("WHEN?", 0, false, false);
document.getElementById('inputheurelivraison').options[1] = new Option("PM", 2, true, true); // new Option(text, value, defaultSelected, selected)
alert ("<? echo t(73); ?>");
}
else {//put am
document.getElementById('inputheurelivraison').options[0] = new Option("WHEN?", 0, true, true);
document.getElementById('inputheurelivraison').options[1] = new Option("AM", 1, false, false);
document.getElementById('inputheurelivraison').options[2] = new Option("PM", 2, false, false);
}
The problem:
Let's say someone fill the form, then choose "AM" as the option and then change the date to "tomorrow", then my scripts run and remove the "AM" choice from the list and choose "PM" as "selected". When the user submit the form, the POST data is "AM" as selected...
Why? I chose "PM" and when I take a look at the HTML it says "PM" as "selected" so why does it not submit that value?
Thanks a bunch in advance
Joe
There is no need to remove all options first, you can remove only the ones you don't want. Something like the following should be suitable (note storage of reference to DOM element so only get once):
var doIt = (function() {
// Reference to removed option
var removedOption;
return function(s) {
// Get reference to select once
var select = document.getElementById('inputheurelivraison');
if (parseInt(datebits[2]) == parseInt(demain)) {
// Store reference to am option then remove it
removedOption = select.options[1];
select.removeChild(select.options[1]);
// Make pm selected (it's now index 1)
select.options[1].selected = true;
// Debug?
alert ("<? echo t(73); ?>");
} else {
// Replace removed option
select.insertBefore(removedOption, select.options[1]);
// Make first option selected
select.options[0].selected = true;
}
}
}());
Alternatively you can move the unneeded option to a hidden select element.
The above is just a proof of concept example, there are many ways to skin the cat, the bottom line is you don't have to delete all the options and recreate the ones you want every time.
Thanks for your answers. But I just found out what was the bug. I'll explain it in case it could help anybody else:
After checking if the "day" = "tomorrow" and changing the form, the script would then POST the data in AJAX to a PHP file. So here was the origin of the problem: I was asking my script to POST the selectedIndex of my dropdown instead of the option[selectedIndex].valueof it. For this reason, my script was returning "AM" as the choice even if "PM" was selected because selectedIndex always start at 0, 1, 2 etc. and my value were AM=1 and PM=2.
So I changed:
document.getElementById("inputheurelivraison").selectedIndex
for:
document.getElementById('inputheurelivraison').options[document.getElementById("inputheurelivraison").selectedIndex].value
when sending the POST value in AJAX and now it's fine.
Hope nobody else makes this error :)
if (document.myform.mycheckbox.checked)
If checkbox is checked, then do something...
...what line of code would do the same thing for a select box option?
if (document.myform.myselectbox.myselection.selected)
Is it something like that? I can't seem to find what it is I'm looking for.
What I'm doing is here:
Link to stuff nada workola
you are looking for:
if (document.myform.myselectbox.selectedIndex != -1)
When there is nothing selected the index returns -1.
If you actually want the internal value or text string for the selected option you can access it by index:
var selObj = document.myform.myselectbox;
var selIndex = selObj.selectedIndex;
var selOptionValue = selObj.options[selIndex].value;
var selOptionText = selObj.options[selIndex].text;
However you need to be aware that the behavior is also a bit dependent on how you have it displayed. With a "single" select element (e.g. a "drop down") if you don't specify that a particular option is "selected" then the first option (index 0) is considered to be selected as that is how it is visually displayed.
<select>
<option>red</option><!-- "selected" by default when rendered -->
<option>orange</option>
<option>yellow</option>
...
</select>
If you have a select element with a size attribute greater than 1 (e.g. 6) then visually there are none selected, thus the element will return -1 by default (if none were selected)
<select size="6">
<option>red</option><!-- NOT "selected" by default when rendered -->
<option>orange</option>
<option>yellow</option>
...
</select>
Either way, you can use code like this to determine what to do:
var mySelect = document.myform.myselectbox;
var selIndex = mySelect.selectedIndex;
if(selIndex != -1){
//an option is selected
if(selIndex == 0){
//first option is selected
} else if(selIndex == 1){
//second is selected
} else if(selIndex == 2){
//third is selected
}
} else {
//no option is selected
}
You could write this using a switch/case statement too, I've just expanded this to indicate a few values