I have HTML drop-downs;
Coded in the below format:
<select name="State" id="State" class="required"/>
<option value="">--Select State--</option>
<option value="AK">Alaska</option>
</select>
I have an error background image that appends to the <select> tag on error. But I would like to remove the background image, once the user has used the drop-down and has currently selected an available option.
So, when the drop down is open and any item is selected via <option> tag hide background image. I don't need help with hiding the background image per se'. Just the logic of detecting when an option has been selected.
I have tried starting with this logic
$('option:selected').css('background', 'none !important');
Here's the caveat you guys may be missing; if there is a scenario when the user toggles back to the default start state - eg in this case 'Select a State' this background image must reappear / restore.
Add a change event on the State dropdown. So whenever the value is not empty, it will hide the error message.
$('#State').change(function() {
if(this.value !== '') {
//hide error
console.log('hide');
} else {
//show error
console.log('show');
}
});
I didn't use an image but its the same idea. I see you are applying styling directly to the element. I would recommend just using a class to apply the image and removing the class when you don't need the image any more:
Fiddle: http://jsfiddle.net/AtheistP3ace/oLrckqzj/
HTML:
<select name="State" id="State" class="required">
<option value="">--Select State--</option>
<option value="AK">Alaska</option>
</select>
JS:
var select = document.getElementById('State');
select.addEventListener('change',
function () {
if (this.value != '') {
this.classList.remove('required');
}
else {
this.classList.add('required');
}
}
);
Also you had this
<select name="State" id="State" class="required"/>
Which should be:
<select name="State" id="State" class="required">
And with jQuery: http://jsfiddle.net/AtheistP3ace/oLrckqzj/1/
var $select = $('#State');
$select.on('change',
function () {
var $this = $(this);
if ($this.val() != '') {
$this.removeClass('required');
}
else {
$this.addClass('required');
}
}
);
This will be fired when an option has been selected, assuming it is different from the currently selected option. It will not fire when the select menu is opened, though. You can probably use on 'click' for that.
$('select').on('change', function (e) {
console.log("changed: ", this, e);
});
To detect whether an option is selected or not, you can do the following:
$('select').change(function()
{
if($(this)[0].selectedIndex == 0 && $(this).val() == "") // check if value is empty and index of the selected option is not zero.
alert("not selected");
else
alert("selected");
});
Example : http://jsfiddle.net/WTkqn/300/
Related
I have the following HTML select:
<select class="form-control" id="band_id" name="band_id">
<option selected="selected" value="">Choose a band...</option>
<option value="66">Adolfo Little</option>
<option value="96">Aisha Bosco</option>
<option value="90">Alize Glover</option>
</select>
I need to build a filter where the condition is the #band_id selected so I made this jQuery code:
$("select#band_id").change(function (ev) {
ev.preventDefault();
var band_id = $('select#band_id');
if (band_id.val() != undefined) {
band_id.attr('selected', 'selected');
}
location.href = '/albums/bands/' + band_id.val();
});
Because the location.href the page gets reloaded and the URL changes so the SELECT is reset and I "loose" the selected value.
I can think in two ways to fix this:
Using AJAX which I don't want because is over complicate something easy
Grab the band_id from the URL and then set the selected property which I don't know how to achieve.
I don't know is there any other way to achieve this. Do you have any other idea? (if it's with an example better)
You can use localStorage for that:
if (localStorage.getItem("band_id")) {
$("select#band_id").val(localStorage.getItem("band_id"))
}
$("select#band_id").change(function (ev) {
ev.preventDefault();
if ($(this).val() != undefined) {
$(this).attr('selected', 'selected');
localStorage.setItem("band_id", $(this).val());
}
location.href = '/albums/bands/' + $(this).val();
});
If we have the value saved - set the value of the select element to that values.
Once we change the value in the select element - save the new value in the localStorage.
Note that I removed the usage of the band_id from this example as it's not needed. You have this you can use inside the change function.
I'm also not sure why you change the selected attribute - you redirect the user immediately to a new page (this change will have no effect at all).
I am having a form where the fields need to change according to my select.
But when I hit the reset the select resets back to default, but the onchange event on the select is not triggered. Is there anyway so that I can add that to my javascript?
I am resetting using a button with type="reset"
$('#newHistoryPart select[name="roundType"]').on('change', function (data)
{
$(".answerType").hide();
selected = $(this).find("option:selected").val();
roundTypeChange(selected);
});
From my comment above, use onreset event instead of onchange:
$('#yourform').on('reset', function(){
// do something
});
What you need to do is, trigger the change event manually when the reset button is clicked. See Fiddle here
$('select').on('change', function ()
{
alert('on change');
});
$('input[type="reset"]').click(function() {
$("select").trigger('change');
});`
you can use
$('select[name="roundType"]').prop('selectedIndex',0);
DEMO HERE
This may help you, replace alert lines with your activity code.
JSFiddle
HTML
<select name="opt" onchange="getval(this)">
<option value="Select" selected disabled>Select</option>
<option value="op1">Option 1</option>
<option value="op2">Option 2</option>
</select>
JavaScript
function getval(sel) {
if (sel.value == "op1") {
alert("Option 1 Selected");
} else if (sel.value == "op2") {
alert("Option 2 Selected");
}
else
{
alert("EXCEPTION !");
}
}
My html code is:
<div class="setting-control">
<select class="on-off" id="custom-cache-pref">
<option value="">Default</option>
<option value="byc">Bypass cache</option>
<option value="basic">Basic caching</option>
<option value="iqs">Ignore query string</option>
<option value="agg">Aggressive caching</option>
<option value="all">Cache everything</option>
</select>
</div>
Usually with casperjs I would use
this.fillSelectors('form[name="formName"]', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
to select option "byc" but this time the "select" element is not embedded in a form!
How can I choose its value in this case?
Adapted from my answer here, you can create your own function that selects an option by value. This changes the selected index which might not trigger the select onChange event.
casper.selectOptionByValue = function(selector, valueToMatch){
this.evaluate(function(selector, valueToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.value.indexOf(valueToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
// dispatch change event in case there is some kind of validation
var evt = document.createEvent("UIEvents"); // or "HTMLEvents"
evt.initUIEvent("change", true, true);
select.dispatchEvent(evt);
}, selector, valueToMatch);
};
casper.start(url, function() {
this.selectOptionByValue('select#custom-cache-pref', "byc");
}).run();
Alternative 1
Judging by the code of __utils__.fill() and casper.fillForm(), the selector of the form doesn't necessarily have to be a form. It may be a div:
this.fillSelectors('div.setting-control', {
'select[id="custom-cache-pref"]': 'byc'
}, false);
Alternative 2
If this still doesn't work, you might need to resort on focusing on the select element in the page context and sending up and down key events to change the value using PhantomJS' page.sendEvent():
this.evaluate(function(){
document.querySelector('select[id="custom-cache-pref"]').focus();
});
this.page.sendEvent('keypress', this.page.event.key.Down);
Coming from this related topic where a user leave a solution and it works, I come with a second part where I forgot to mention that the SELECT element has a .select2() applied. If you test a live example here on this Fiddle you'll see how the button#btnBuscar is enable any time a input change and gets values or when SELECT changes the default option but if I delete the values from the INPUTs or choice back the default option in the SELECT then the button is not disabled, where is the error on the solution provided:
$(':input').on('input change', function () {
var completed = $(':input').filter(function () {
return !!this.value;
}).length > 0;
$('button#btnBuscar').prop('disabled', !completed);
});
Either your could change:
<option selected="selected" value="-1">-- SELECCIONAR --</option>
To:
<option selected="selected" value="">-- SELECCIONAR --</option>
OR adjust the js code to:
$(function(){
$('select.toSelect2').select2();
$(':input').on('input change', function () {
var completed = $(':input').filter(function () {
return !!this.value && !$(this).is('select') ||
(this).is('select') && +this.value > -1;
}).length > 0;
$('button#btnBuscar').prop('disabled', !completed);
});
});
DEMO
I'm sure there is a very simple solution, I just don't know it...
I have a text box and a selector. The first option in the selection is custom, where they can input with the text box. If they select something else, the text box becomes disabled.
I'm guessing the solution will be to put an onclick to test the value, but is there another way?
Use the change event, not the click event.
var select = document.getElementById('mySelect'),
textbox = document.getElementById('myTextbox');
function onSelectChanged()
{
console.log(select.selectedIndex);
textbox.disabled = select.selectedIndex !== 0;
}
if (select.addEventListener)
{
select.addEventListener('change', onSelectChanged, false);
}
else
{
// !##$ing IE support, of course
select.attachEvent('onchange', onSelectChanged, false);
}
Demo: http://jsfiddle.net/mattball/pJMWN/
dont think onclick will serve your purpose better use onchange event in the selection and check for the selected value not equal to custom and then enable/disable your text box...
Hope this helps you,,,,
You would use an onchange listener on your select element. I also recommend using an onkeyup listener because some browsers do not fire onchange events when the user changes the select-box value using the keyboard. Here is some example code:
<select id="mySelect" name="name" onkeyup="this.onchange();" onchange="selectChanged(this);">
<option value="-1">(custom value)</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="text" id="customText" name="customOption" value="" />
<script>
window.selectChanged = function(theSelect) {
var textInput = document.getElementById("customText");
if (theSelect.selectedIndex == 0) {
textInput.disabled = undefined;
}
else {
textInput.disabled = true;
textInput.value = "";
}
};
</script>
Example: http://jsfiddle.net/tB2Am/2/