Binding an event handler to an HTML select.option - javascript

I want to show a warning message if a user selects a specific option, but the warning isn't appearing. How can I modify my code so that this works correctly? Here is a demo on jsFiddle which reproduces the problem?
HTML :
<input type="text" id="mail_address"/>
<select>
<option value='google.com'>google.com</option>
<option onClick="warningaa()" value=''>Don't send mail</option>
</select>
JS:
function warningaa() {
alert('If you choose this option, you can not receive any information');
}

You can not use on click action in dropdown option. One solution is to use change on select element:
html
<input type="text" id="mail_address" />
<select onchange="warningaa(this);">
<option value='google.com'>google.com</option>
<option value='error'>error</option>
</select>
js
function warningaa(obj) {
if(obj.value == "error") {
alert('If you choose this option, you can not receive any infomation');
}
}
fiddle

The option tag does not support the onclick event. Use the onchange event on the select instead.
HTML
<input type="text" id="mail_address"/>
<select id="selectbox" onchange="warning(this)">
<option value='google.com'>google.com</option>
<option value='warning'>Do not send me any kind of shit</option>
</select>
JS
function warning(obj) {
if(obj.value == 'warning') {
alert('If you choose this option, you can not receive any infomation');
}
}

You need to set an event handler on the SELECT element, and watch the "value" of select, as below:
document.getElementById('mySelect').addEventListener('change', warn, true);
function warn(e) {
e.preventDefault();
e.stopPropagation();
if (e.currentTarget.value === 'the value you want') {
// do something
} else {
return;
}
The key here is using CHANGE event vs CLICK, since you want to react to a "change in value" and if that value = something, warn the user.
using addEventListener is also a better approach overall, it clearly distinguishes your HTML from your JavaScript.
More on this here:
https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener
and here:
https://developer.mozilla.org/en/docs/Web/API/Event

Related

How do I attach an event to an array of select boxes?

I have an array of select boxes, with a class "taskcompleted". I want to be able to do something when a box is changed.
<select class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
I have used this javascript code
function initselects() {
var myselects = $('.taskcompleted');
myselects.each( function(){ // any select that changes.
console.log( $(this).val() );
}).change();
}
When the page loads, it is logging a change for each select box. I do not want this to happen. I want to only log a change after the page as has loaded.
You can use change() to attach the event to each select, like this:
function initselects() {
$('.taskcompleted').change(function() {
console.log($(this).val());
});
}
Something like this you mean? This will add change handlers to all selects with class taskcompleted
The problem you have it that you're adding .change() to the end which actually triggers the change you don't want to happen - so instead, just listen for it
function initselects() {
$('select.taskcompleted').on('change', function() {
// do something
});
}
If you don't want the logging at page load, then simply remove change() from the end.
In general you can use it like that
JavaScript:
var myselects = $('.taskcompleted');
myselects.change( function(){
console.log($(this).attr('name') + ': ' + $(this).val() );
});
HTML:
<select name="1stselectbox" class = "taskcompleted" >
<option value="No">No</option>
<option value="Yes">Yes</option>
</select>
<select name="2ndselectbox" class = "taskcompleted" >
<option value="Maybe">Maybe</option>
<option value="dontknow">I don't know</option>
</select>
So you set the change listener directly on the jQuery objects, no need to use a loop (each). The example above will even print which select box was selected (might be useful). E.g. the output will be when changing the first box to Yes: 1stselectbox: Yes
JSFiddle: https://jsfiddle.net/x8jwy92h/

How to change the default required select option field message using jquery

How can I change the default Message of a required select option field. Its a variation of WooCommerce's product. I added the property dynamically and try to change the message my bellow code able to change the message but it not works . It always appearing no matter if there is a selected value or not.
JsFiddle
HTML
<select id="color" class="" name="attribute_color" data-attribute_name="attribute_color">
<option value="" selected="selected">Choose an option</option>
<option value="White" class="attached enabled">White</option>
<option value="Black" class="attached enabled">Black</option>
</select>
Script
jQuery(document).ready(function($) {
$('select#color').prop('required', true);
if( !$('select#color').has('value').length > 0 ) {
$('select#color').attr("oninvalid", "this.setCustomValidity('Please select a color')");
}else{
$('select#color').removeAttr("oninvalid", "this.setCustomValidity('Please select a color')");
}
});
JsFiddle
From the msdn docs:
Constraint API's element.setCustomValidity()
The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.
It means that once you setCustomValidity error the input will be considered as invalid till you wont reset it by passing empty string.
What I did below is checking when select event happened and check if select has value if it doesn't then set error if it has then reset error.
FIDDLE
jQuery(document).ready(function($) {
var selectColor = $('select#color');
selectColor.prop('required', true);
/* Check if there is no selected value on ready if not mark select as invalid */
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}
/* Do the same check when select value changed */
selectColor.on('change', function(){
if(!selectColor.val()){
selectColor[0].setCustomValidity('Please select a color');
}else{
selectColor[0].setCustomValidity('');
}
})
});
Try this one
$('select#color').on('invalid', function () {
return this.setCustomValidity('Please select a color.');
}).on('change', function () {
return this.setCustomValidity('');
});

How do I pass the value of drop down with form submit?

I have these 2 drop downs:
I have to provide values of Select Item drop down based on the value chosen in the Select Category drop down.
This is my PHP for Select Category drop down:
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onclick="document.form.submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
But nothing is happening. How do I do it?
Try onchange instead of onclick
<form>
...
<select name="category" id="category" value="category" class="form-control ddplaceholder" style="width:220px;font-size:18px;font-family:Roboto;" onchange="document.forms[0].submit();">
<option value="" disabled selected>Select Category</option>
...
<input type="submit" name="submit" style="width:20%;padding:15px;" value="Update"</input>
...</form>
Two more things you should notice
onchange="document.form.submit();" this will not work because
document doesn't have a property form it is forms so you should
use onchange="document.forms[0].submit();"
You have named your submit button as submit which will prevent the
form from submitting because submit is a javascript function so
rename your submit button to something else.
If you dont have many possible values for your dropdowns, you can use plain old javascript for that purpose. See this http://jsfiddle.net/mplungjan/65Q9L/, but it requires all values to be loaded at once on the page load like this:
var stateObject = {
"California": {
"Monterey": ["Salinas", "Gonzales"],
"Alameda": ["Oakland", "Berkeley"]
},
"Oregon": {
"Douglas": ["Roseburg", "Winston"],
"Jackson": ["Medford", "Jacksonville"]
}
}
document.form.submit(); will submit the form which is not the requirement.
Instead you need to make an ajax call with the selected value from first dropdown and the response will be use to build the options of second dropdown.
use change which will trigger on change of option
$('category').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value; // will give value of selected option
$.ajax({
url:"someUrl", // this url will return response from backend
// other methods
success:function(response){
//use this response to build the second dropdown
}
})
});

How to check select statement choice before submission

I have a select area for the user:
<select class="span12" placeholder="Enquiry Type" name="enquiry" id="enquiry">
<option value='' selected></option>
<option value='cv'>Submit CV</option>
<option value='vacancy'>Submit Vacancy</option>
</select>
I have a hidden field in the form which allows the user to upload their cv. I now need it so that if the user selects submit cv, the field will display itself.
<input type="file" name="cv" accept="application/pdf,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document" style="display:none;">
I know that i would be able to check the user input of the select using an on click function. Is there a way of doing it without that (there and then)? And then if that option is selected, display the hidden file upload.
Try this:
$('#enquiry').on('change', function(e) {
if($(this).val() === "cv") {
$('input[name="cv"]').show();
}
});
This works:
http://jsfiddle.net/dL8evt33/
:)
You can achieve this by hooking to the change event of the select and checking the selected value. You can then use toggle() to hide or show the input as needed. Try this:
$('#enquiry').change(function() {
$('input[type="file"]').toggle($(this).val() == 'cv');
});
Example fiddle
remove display: none; first now do write this code.
$("[id$=fileupload]").hide();
if("[id$=enquiry]").val('cv')
{
$("[id$=fileupload]").show();
}
else
{
$("[id$=fileupload]").hide();
}
On change event you can display the input type file using its id. Give 'file' as id to hidden field -
$('#enquiry').on('change', function() {
if("cv" == this.value){
jQuery("#file").show(); // or jQuery("#file").toggle();
}
});

Jquery event for option box and typing action

I am doing the jquery event programming for option box for premium box.
For example, i can type on the option box.
So, I type in the option box instead of selecting my select option box.
the following code is the example:
But seems like it is not correct. Is the event is 'change' event ?
My HTML code is as following:
<div id = 'divContent'>
<select id="my_id" style="width: 120px;"
onchange="$('input#my_id').val($(this).find('option:selected').text());"
name="my_id">
<option value="10000">10000</option>
<option value="20000">20000</option>
<option value="30000">30000</option>
<option value="50000">50000</option>
<option value="80000">80000</option>
<option value="100000">100000</option>
</select>
</div>
You need to replace my_id with the id of your select box:
$("#divContent").on('change', "select[id='my_id']", function () {
Will work only when you have a select like:
<select id="my_id">
...
I don't see any elements with the id divContent so change the first line to
$("select[id='my_id']").on('change', function () {
Secondly, even when the code is working, with the example given, there won't be any alerts because none of the if statements will evaluate to true
You have a syntax error here -
if (selectedValue = '') {
alert("Please enter Premium")
}
it should be == not =
if (selectedValue == '') {
alert("Please enter Premium");
}
you can also use -
if(!selectedValue) or if(selectedValue == null)

Categories

Resources