This question already has answers here:
JavaScript - a way check if an option of the <select> tag is selected
(3 answers)
Closed 8 years ago.
I have a dropdown list that is generating dynamically using PHP. Its rendered HTML is something similar to below markup -
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
Using this markup, just I want to check whether item is selected or not using JavaScript. If it is not selected an item, then I need to get an alert message.
I tried it something like this. But I can not get it to work.
JavaScript -
var email = document.getElementById("email");
var selectedValue = email.options[email.selectedIndex].value;
if (selectedValue == '') {
alert("Please select a email");
}
Hope somebody may help me out.
Thank you.
You should listen to the change event of the select element and then parse the value of the selected option as an integer (parseInt(email.options[email.selectedIndex].value, 10)):
Example Here
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
var email = document.getElementById("email");
email.addEventListener('change', function (e) {
var selectedValue = parseInt(email.options[email.selectedIndex].value, 10);
if (selectedValue === 7) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
... since you're validating whether an option is selected, you would use something more along these lines:
Example Here
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
var email = document.getElementById("email"),
validationButton = document.getElementById('validationButton');
validationButton.addEventListener('click', function (e) {
var selectedValue = email.options[email.selectedIndex] ? email.options[email.selectedIndex].value : null;
if (!selectedValue) {
alert("Please select a email");
}
});
<select size="8" id="email" name="email">
<option value="6" data-userId="uid6">kamala#gmail.com</option>
<option value="8" data-userId="uid8">tk#g.com</option>
<option value="3" data-userId="uid3">myexample.com</option>
<option value="7" data-userId="uid7">samadhi#gmail.com</option>
<option value="2" data-userId="uid2">facebook.com</option>
<option value="4" data-userId="uid4">lankainstitute.com</option>
</select>
<button id="validationButton">Check if selected</button>
Related
I would like to add the values from checkboxes and a dropdown menu using JavaScript (no JQuery).
My first question is how best to do this... my code is bellow.
Second question is are there disadvantages to using anonymous functions to do this?
Thank you!
https://jsfiddle.net/Buleria28/4ysvgkz8/
HTML
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum" > box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum" > box 3
</label>
<br/><br/>
<select id="select" name ="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/><br/>
Total: $<span id="payment-total">0</span>
JavaScript
/*To get checkbox values*/
var inputs = document.getElementsByClassName('sum'),
total = document.getElementById('payment-total');
for (var i=0; i < inputs.length; i++) {
inputs[i].onchange = function() {
var checkAdd = this.value * (this.checked ? 1 : -1);
total.innerHTML = parseFloat(total.innerHTML) + checkAdd;
}
}
/*To get select values*/
var dropdown= document.getElementById("select");
for(j=0; j<dropdown.options.length;j++){
dropdown[j].onchange = function() {
if (dropdown[i].options.checked){
var selectAdd = dropdown.options[dropdown.selectedIndex].value;
total.innerHTML = parseFloat(total.innerHTML) + selectAdd;
}
}
}
Some things I want to point out:
Use addEventListener to bing event handlers
You can use anonymous functions but it's clearer when you declare it and give it a meaningful name
Don't keep total sum in the HTML element. Keep it in the variable and then insert it into HTML.
I would do it like that:
var checkboxes = document.querySelectorAll('.sum')
var select = document.querySelector('#select')
var total = document.querySelector('#payment-total')
var checkboxesTotal = 0
var selectTotal = 0
checkboxes.forEach(function(input) {
input.addEventListener('change', onCheckboxSelect)
})
select.addEventListener('change', onSelectChange)
function onCheckboxSelect(e) {
var sign = e.target.checked ? 1 : -1
checkboxesTotal += sign * parseInt(e.target.value, 10)
renderTotal()
}
function onSelectChange(e) {
var value = parseInt(e.target.value, 10)
if (!isNaN(value)) {
selectTotal = value
renderTotal()
}
}
function renderTotal() {
total.innerHTML = checkboxesTotal + selectTotal
}
<label class="checkbox" for="Checkbox1">
<input value="50" type="checkbox" class="sum"> box 1
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 2
</label>
<label class="checkbox">
<input value="50" type="checkbox" class="sum"> box 3
</label>
<br/>
<br/>
<select id="select" name="select">
<option class="sum"></option>
<option value="1" class="sum">option 1</option>
<option value="2" class="sum">option 2</option>
<option value="5" class="sum">option 3</option>
</select>
<br/>
<br/> Total: $<span id="payment-total">0</span>
Here is a correction for JS regarding select element, I added inline comments, please check them for clarification:
/*To get select values*/
var dropdown = document.getElementById("select");
dropdown.onchange = function() {
var value = parseInt(this.value); // gets the selected value from "select" and tries to convert it to int
if(!isNaN(value)) { // if conversion is OK, i.e. it was a number
total.innerHTML = parseFloat(total.innerHTML) + value; // this line is copied from your previous code
}
}
I have a set of checkboxes from
<input type="checkbox" name="parts_hoses" id="parts-cb1" value="1">
through id="parts-cb6"
I have a select box of #send-product
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select>
that when it is on its default value, "wall-mounted", the checkboxes are enabled (as they are by default), but when I switch that to another option in the list... I'd like to disable the checkboxes.
Here is my JS so far (doesn't work):
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
if (selectBox.value == 'wall-mounted') {
checkBoxes.disabled = false;
} else {
checkBoxes.disabled = true;
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
What am I doing wrong? Any help is appreciated!
Here's a fiddle: https://jsfiddle.net/cwkgsuq1/
You're missing to loop your checkboxes Array collection.
plain JS is not jQuery, therefore "checkBoxes.disabled = false;" will not work.
Instead:
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = false;
}
So your code simplified could look like:
function switchProduct() {
var checkBoxes = document.querySelectorAll('input[type="checkbox"][id^="parts-cb"]');
var selectBox = document.getElementById('send-product');
for(var i=0; i<checkBoxes.length; i++) {
checkBoxes[i].disabled = selectBox.value == 'wall-mounted';
}
}
document.getElementById('send-product').addEventListener('change', switchProduct);
switchProduct();
<select name="send_product" id="send-product">
<option value="wall-mounted" selected>Wall-mounted (Default)</option>
<option value="freestanding">Freestanding</option>
<option value="third_party">Third Party</option>
</select><br><br>
<input type="checkbox" id="parts-cb1" value="1">
<br>
<input type="checkbox" id="parts-cb2" value="1">
<br>
<input type="checkbox" id="parts-cb3" value="1">
I have this form with the following options:
<select name="choices" id="options" onchange="showText()">
<option value="">Select amount</option>
<option value="1">100PHP</option>
<option value="2"> 500PHP</option>
<option value="3"> 1000PHP</option>
<option value="4"> 2000PHP</option>
<option value="5"> 3000PHP</option>
<option value="6"> 4000PHP</option>
<option value="7"> 5000PHP</option>
<option value="8"> 10,000PHP</option>
<option value="others"> others..</option>
</select>
<div class="control-group" id="show" style="display:none;">
When the user selects option 1-8, it will display the amount. I've successfully done that through this javascript:
function showText(){
var value = document.getElementById('options').value;
if(value == '1'){
var amount = document.getElementById("amount");
amount.value = "100";
document.getElementById('show').innerHTML =
"<br><br><font size =+1><b>Amount P 100 </b></font>"
document.getElementById('show').style.display = "block";
}
else if(value == '2'){
var amount = document.getElementById("amount");
amount.value = "500";
document.getElementById('show').innerHTML = "<br><br><font size =+1><b>Amount P 500 </b></font>"
document.getElementById('show').style.display = "block";
}
//up to option 8
Now, when the user selects 'others' it will display another input field. The value that the user will input will be the value option 'others':
else if (value == 'others'){
document.getElementById('show').innerHTML = "<br><div class='control-group'><label class='control-label'>Enter Amount</label><div class='controls'><input type='text' id='other_amount' name='other_amount'> ";
var amount = document.getElementById("other_amount").value;
document.getElementById('show').style.display = "block";
}
Unluckily, I was not successful in getting the value of the second input to be the value of the first input. I hope you could help! Thank you!
First of all, you can improve your code quite a lot:
function showText(){
var value = document.getElementById('options').value;
if(value == '-1'){
//Other
document.getElementById('hidden').style.display = 'block';
}
else {
document.getElementById('hidden').style.display = 'none';
var amount = document.getElementById("amount");
amount.value = value;
document.getElementById('show').innerHTML = "<br><br><font size =+1><b>Amount P " + value + "</b></font>"
document.getElementById('show').style.display = "block";
}
}
Where you change your html to:
<select name="choices" id="options" onchange="showText()">
<option value="">Select amount</option>
<option value="100">100PHP</option>
<option value="500">500PHP</option>
<option value="1000">1000PHP</option>
<!-- (...) -->
<option value="-1"> others..</option>
</select>
I'd also suggest adding the "hidden" input for when they choose others already in your html, but set it invisible:
<div id="hidden" style="display:none;"class='control-group'>
<label class='control-label'>Enter Amount</label><div class='controls'>
<input type='text' id='other_amount' name='other_amount' onChange='otherText()'/>
</div>
</div>
Now, when they select others.. with value -1 you want to show an input where they can choose their own value:
if (value == -1) {
document.getElementById('hidden').style.display = 'block';
}
Now we just need the function otherText() which shouldn't be a problem:
function otherText() {
document.getElementById('amount').value = document.getElementById("other_amount").value;
}
Working jsFiddle
I want to change option values as per the input value. For example if i put value02 in input then the select should show options having title="value02" other options will hide.
<input type="text" name="fname" value="" id="fname">
<select name="program" id="program">
<option>Select Program Type</option>
<option value="1" title="value01">1</option>
<option value="2" title="value01">2</option>
<option value="1" title="value02">1</option>
<option value="2" title="value02">2</option>
<option value="1" title="value03">1</option>
<option value="2" title="value03">2</option>
</select>
Please help
I think this is the ANSWER you looking for
WORKING:DEMO
HTML
<input type="text" name="fname" value="" id="fname">
<select name="program" id="program">
<option>Select Program Type</option>
<option value="1" title="value01">01 1</option>
<option value="2" title="value01">01 2</option>
<option value="1" title="value02">02 1</option>
<option value="2" title="value02">02 2</option>
<option value="1" title="value03">03 1</option>
<option value="2" title="value03">03 2</option>
</select>
JS/JQuery
$(document).mouseup(function (e)
{
var container = $("select");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
$("#program option[title='value01']").show();
$("#program option[title='value02']").show();
$("#program option[title='value03']").show();
}
});
$("select").click(function()
{
var getVal = $("input[type=text]").val();
if(getVal == "value01")
{
$("#program option[title='value02']").hide();
$("#program option[title='value03']").hide();
}
else if(getVal == "value02")
{
$("#program option[title='value01']").hide();
$("#program option[title='value03']").hide();
}
else if(getVal == "value03")
{
$("#program option[title='value01']").hide();
$("#program option[title='value02']").hide();
}
else
{
}
});
Assuming your question means that you want to hide <option> tags that don't match the title that the user typed (so only the matching options are available in the <select>), you can do it like this:
You can monitor changes to the fname field and upon each change see if the current value of the fname field matches any of the titles and, if so, hide the options that don't match, leaving only the matching options. If none match, then show all the options.
$("#fname").on("input", function() {
var option;
if (this.value) {
var sel = $("#program");
option = sel.find('option[title="' + this.value + '"]');
}
if (option && option.length) {
// show only the matching options
sel.find("option").hide();
option.show();
} else {
// show all options
sel.find("option").show();
}
});
Try this. It disables all the options. And add new option that is entered from input field. You need to press enter after entering value in input field.
$(document).ready(function() {
$('#fname').bind('keypress', function(e) {
var code = e.keyCode || e.which;
if (code == 13) { //Enter keycode
$("#program").append($('<option/>', {
value: $("#fname").val(),
title: $("#fname").val(),
text: $("#fname").val()
}));
$("#program option[value!=" + $("#fname").val() + "]").attr('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="fname" value="" id="fname">
<select name="program" id="program">
<option>Select Program Type</option>
<option value="1" title="value01">1</option>
<option value="2" title="value01">2</option>
<option value="1" title="value02">1</option>
<option value="2" title="value02">2</option>
<option value="1" title="value03">1</option>
<option value="2" title="value03">2</option>
</select>
Use jquery. Get the value of the input and search the option for that value and set the value. Try with -
$('#program').val($('#program option[title=' + $('#fname').val() + ']').val())
Try this...
<input type="text" name="fname" value="" id="fname">
<select name="program" id="program">
<option>Select Program Type</option>
<option value="1" title="value01">1</option>
<option value="2" title="value01">2</option>
<option value="1" title="value02">1</option>
<option value="2" title="value02">2</option>
<option value="1" title="value03">1</option>
<option value="2" title="value03">2</option>
</select>
$('#fname').on('blur', function(){
var value=$("#fname").val();
$('#program').val($('#program option[title=' + value + ']').val());
});
demo:https://jsfiddle.net/qrecL29u/2/
And without jQuery
var field = document.getElementById('fname'),
select = document.getElementById('program');
field.addEventListener('keyup', function(evt) {
for (var i = 0; i < select.children.length; i++) {
if (select.children[i].title !== field.value) select.children[i].style.display = 'none';
else select.children[i].style.display = 'block';
}
});
<input type="text" name="fname" value="" id="fname">
<select name="program" id="program">
<option>Select Program Type</option>
<option value="1" title="value01">1</option>
<option value="2" title="value01">2</option>
<option value="1" title="value02">1</option>
<option value="2" title="value02">2</option>
<option value="1" title="value03">1</option>
<option value="2" title="value03">2</option>
</select>
I want a drop down element where user can select from available options or select enter value option which in turn allows to enter value.
I specifically want that user can enter value only when they select "Enter a value " option.
Here is what I have tried so far.
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
} else {
x.find('.holder').val(x.find('option:selected').text());
}
});
JS fiddle
however it wont work properly if i click the enter value option again.
I think there are many plugins that do what you want but if you want to create your own, it's a basic and simple solution.
You can create a select and a textbox with display:none like this:
<select id="ddlDropDownList">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
<option value="3">Item 3</option>
<option value="-1">Enter Value</option>
</select>
<input id="txtTextBox" type="text" />
<style>
#txtTextBox{
display:none;
}
</style>
then try this JQuery:
$("#ddlDropDownList").change(function(){
if($(this).val() == '-1'){
$("#txtTextBox").fadeIn();
}else{
$("#txtTextBox").fadeOut();
}
});
Check JSFiddle Demo
I have forked your JSFiddle to http://jsfiddle.net/pwdst/4ymtmf7b/1/ which I hope does what you wanted to achieve.
HTML-
<div class="ginput_container">
<label for="input_1_4">Select option</label>
<select class="medium gfield_select" id="input_1_4" name="input_4" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<div>
<label class="hidden-label" for="input_1_4_other">Other value</label>
<input class="holder" id="input_1_4_other" disabled="disabled" name="input_1_4_other" placeholder="None" type="text" />
</div>
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var $this = jQuery(this);
var val = $this.val();
var holder = $this.parent().find('.holder');
if (val === "*"){
holder.val('');
holder.removeAttr('disabled');
holder.focus();
} else {
holder.val(this.options[this.selectedIndex].text);
holder.attr('disabled', 'disabled');
}
});
When the "Enter value" option is chosen then the input box is enabled, value set to an empty string, and it is focused. If another option is chosen then the text input is disabled again, and the text value from the select list is used.
Thanks guys
I guess i have found my answer
HTML-
<div class="ginput_container">
<select name="input_4" id="input_1_4" class="medium gfield_select" tabindex="15">
<option value="0">None</option>
<option value="155">1-70</option>
<option value="185">71-250</option>
<option value="*">Enter value</option>
</select>
<input type="text" value="None" class="holder" >
</div>
JavaScript-
jQuery(".gfield_select").change(function() {
var val = jQuery(this).val();
var enter = jQuery(this).parent().find('option:selected').text();
var x = jQuery(this).parent();
if (enter ==="Enter a value" || enter === "Enter value"){
var holder = x.find('.holder');
holder.val('');
holder.prop('disabled',false);
holder.focus();
jQuery(this).val("0"); // Change select value to None.
} else {
x.find('.holder').val(x.find('option:selected').text());
x.find('.holder').prop('disabled',true);
}
});
JS FIDDLE