Javascript - Make an element dissapear if an option is selected - javascript

I have a list of countries in a drop-down menu
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
<p><input type="text" name="state_field" value="" id="state"></p>
My goal is: If value 3 is selected, the input field "state" disappears. If option 1 or 2 are selected, it should show the field "state".
In case the user has already entered a value in the input field "state" (because option 1 or 2 were previously selected) and he changes it to option 3, the code should first erase the value entered in the state field and then make that field disappear.
How would the Javascript code look like?
I appreciate your help!
UPDATE:
Apparently there is a function already running "onchange", so that the HTML looks this way:
<select name="<select name="country_List" onchange="checkCountry();" id="countries">
<option value="">––> Select</option>
<option value="1">USA</option>
<option value="2">Canada</option>
<option value="3">Mexico</option>"
<option value="4">Argentina</option>"
<option value="5">Australia</option>"
</select>
This seems to be interfering with the codes suggested for this case. Is it there any way to run the code to hide the "state" after the "onchange" function "checkCountry()" has been run?

First you need to validate your html; you're missing a closing </select> tag. Second, the textbox has to be disabled when not required so that it is not included in the form data when the form is submitted. The following should meet your requirements:
$('#countries').on('change', function() {
if( $.trim( this.value ) === '3' ) {
$('#state').val('').prop('disabled', true).closest('p').hide();
} else {
$('#state').prop('disabled', false).closest('p').show();
}
});
$('#countries').on('change', function() {
if( $.trim( this.value ) === '3' ) {
$('#state').val('').prop('disabled', true).closest('p').hide();
} else {
$('#state').prop('disabled', false).closest('p').show();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
</select>
<p><input type="text" name="state_field" value="" id="state"></p>
UPDATE
And this should meet your updated requirements; you would just update the logic so you end up with the least number of clauses or boolean expressions in the if condition:
$('#countries').on('change', function() {
if( $.trim( this.value ) === '2' || $.trim( this.value ) === '1') {
$('#state').prop('disabled', false).closest('p').show();
} else {
$('#state').val('').prop('disabled', true).closest('p').hide();
}
})
.change();
$('#countries').on('change', function() {
if( ['1','2'].indexOf( this.value ) > -1 ) {
$('#state').prop('disabled', false).closest('p').show();
} else {
$('#state').val('').prop('disabled', true).closest('p').hide();
}
})
.change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1">USA</option>
<option value="2" selected="">Canada</option>
<option value="3">Rest of the World</option>
</select>
<p><input type="text" name="state_field" value="" id="state"></p>
Please note that .change() triggers the change event when the page loads so that if the value is not 1 or 2, the textbox will be hidden.

in javascript:
<script>
function show(mode)
{
document.getElementById('state').style.visibility = (mode) ? 'visible' : 'hidden';
}
<script>
<select name="country_list" id="countries"><option value="">Please select</option>
<option value="1" onclick="show(true)">USA</option>
<option value="2" onclick="show(true)">Canada</option>
<option value="3" onclick="show(false)">Rest of the World</option>
<p><input type="text" name="state_field" value="" id="state"></p>

JSFIDDEL
$( "select#countries" )
.change(function () {
if($("select#countries option:selected").attr("value")=="3"){
$("select#countries").hide();
$("#state").show();
$("#state").val($("select#countries option:selected").text());
}else{
$("#state").hide();
$("select#countries").show();
$("#state").val("");
}
});
$( "#state" )
.change(function () {
if($("#state").val()==""){
$("#state").hide();
$("select#countries").show();
}else{
}
});
JSFIDDEL

Related

How can I pass a value from input field to a select option using jquery?

I'm using the following code to pass a value from a select option to a given input field.
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
$("#meta_itemcondition").val(conditionofitem);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New">
But how can I pass the value of the input field back to the select option value using jQuery?
I am not sure what you are exactly looking, however, as per my understanding I have modifed your code samples.. You can check below snippet.
$( document ).ready(function() {
var conditionofitem = $("#meta_itemcondition").val();
$(".itemconditionmenu").val(conditionofitem);
});
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
if(conditionofitem == '') {
$("#meta_itemcondition").val('Choose Condition');
} else {
$("#meta_itemcondition").val(conditionofitem);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New">
Please check and let me know if you have any further queries.
Try this
$("#addOption").click(function(){
$("#itemconditionmenu").append('<option value="'+$("#meta_itemcondition").val()+'" selected="selected">'+$("#meta_itemcondition").val()+'</option>');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="itemconditionmenu">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input id="meta_itemcondition" type="text" value=""></input>
<button id="addOption">ADD</button>
Example for the same: Blur out your input and value option will be added to select dropdown
$(".itemconditionmenu").change(function() {
var conditionofitem = $(this).val();
$("#meta_itemcondition").val(conditionofitem);
});
$("#meta_itemcondition").blur(function() {
var inputValue = $(this).val();
var o = new Option(inputValue, inputValue);
$(o).html(inputValue);
$("#itemcondition").append(o);
$("#itemcondition").val(inputValue);
});
$( document ).ready(function() {
var value = $("#meta_itemcondition").val();
console.log(value)
var alreadyOption = false;
$("#itemcondition option").each(function()
{
alreadyOption = $(this).val() === value;
if(alreadyOption) {
$("#itemcondition").val(value);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<select id="itemcondition" class="itemconditionmenu">
<option value="">Choose Condition</option>
<option value="New">New</option>
<option value="Used">Used</option>
</select>
<input id="meta_itemcondition" type="text" value="New"/>
Here you can find inline functionality
if you enter a value in textbox value append in drop-down
if you select drop-down value auto set in textbox.
Note: add value in textbox change just input focus
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="jsSelect" onchange="$('.jsTextBox').val($(this).val())">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input class="jsTextBox" onchange="if($(this).val()!=''){$('.jsSelect').append($('<option></option>').attr('value',$(this).val()).text($(this).val()));$('.jsSelect').val($(this).val());}" type="text" value="">

JQuery : Assign null to selected dropdown value

I have two dropdowns. I want the second dropdown, Assign value to be set to null when the specific value which is student from the first dropdown is chosen.
First dropdown:
<select name="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
This is the second dropdown which is hidden, shown only when Reg with value admin is chosen.
<select name="Assign">
<option value="">Choose</option>
<?php
$sql=odbc_exec($conn,'SELECT AssignCd, AssignNm FROM AssignList');
if(odbc_fetch_row($sql))
{
$AssignCd= odbc_result($sql, "AssignCd");
$AssignNm= odbc_result($sql, "AssignNm");
echo "<option value='".$AssignCd."'>".$AssignNm."</option>";
}
?>
</select>
I tried by doing the following but it doesn't work.
Please Help.
if($("#Reg").val("student");) {
$("#AssignCd").val("");
$("#AssignNm").val("");
}
UPDATED:
When Admin is selected, Assign with admin is chosen will be automatically selected. The problem is when I change my option to Student, the supposed value student is chosen is not shown.
How can I make the Assign value of both Admin and Student stay as it is and not jumbled up between them?
This is my code :
fiddle
$(document).ready(function() {
$("#Reg").on("change", function() {
if ($(this).find("option:selected").text() === 'Admin') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').attr("disabled",true).prop("selected", false).wrap('<span>');
$('select[name="Assign"] option[name="admin_assign"]').prop('selected',true);
}
else if ($(this).find("option:selected").text() === 'Student') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').prop('selected',true);
} else {
$("#Assign").hide().attr("disabled"," ");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign" id="Assign">
<option value=" ">Choose</option>
<option name ="student_assign" value="student_assign">student is chosen</option>
<option name ="admin_assign" value="admin_assign">admin is chosen</option>
</select>
$('select[name="Reg"]').on('change', function() {}) this will trigger when you select an option in your select
$(this).find("option:selected").val() == "student" this will see if you have select an option with value "student"
$('select[name="Assign"] option[value="AssignCd"]').text(""); this sets the text of the option with value = AssignCd to empty
This is how far we can go without showing us your generated html for <select name="Assign">
$('select[name="Reg"]').on('change', function() {
if ($(this).find("option:selected").val() == "student") {
$('select[name="Assign"] option[value="AssignCd"]').text("");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign">
<option value="AssignCd">AssignNm</option>
</select>
Update
There is no need to use .wrap() as far as i can see, use .hide() / .show() look at the example below.
$(document).ready(function() {
$("#Reg").on("change", function() {
if ($(this).find("option:selected").text() === 'Admin') {
$("#Assign").show();
$('select[name="Assign"] option[name="student_assign"]').attr("disabled", true).prop("selected", false).hide();
$('select[name="Assign"] option[name="admin_assign"]').prop('selected', true);
} else if ($(this).find("option:selected").text() === 'Student') {
$('select[name="Assign"] option[name="student_assign"]').attr("disabled", false).prop("selected", true).show()
$('select[name="Assign"] option[name="student_assign"]').prop('selected', true);
} else {
$("#Assign").hide().attr("disabled", " ");
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
<select name="Assign" id="Assign">
<option value=" ">Choose</option>
<option name ="student_assign" value="student_assign">student is chosen</option>
<option name ="admin_assign" value="admin_assign">admin is chosen</option>
</select>
<select name="Reg" id="Reg">
<option value="">Choose</option>
<option value="admin">Admin</option>
<option value="student">Student</option>
</select>
First of all #<selector> is used to select Dom elements which have an id <selector>. You cannot access them with the name attribute and id selector.
As for your issue. you need to use the on change event of the first drop down to decide the visibility of the second drop down.
<select name="Assign" id="Assign">
<option value="">Choose</option>
....
....
$('#Assign').hide(); // first hide it so they cannot see it
$(document).on('change', '#Reg', function(e){
if($(this).val()=='admin'){
$('#Assign').show();
}else{
$('#Assign').val('').hide();
}
})

How to check If both select and input field is selected and filled up using jQuery?

I have a html form where a select field and input box exist and I am using 2 class for that which is work_phone_class and work_phone_class_input.
I am calling ajax by trigger a save button with a class when select field value is changed or any option selected AND again calling ajax when user complete typing on input box. So that I am using following jQuery code :
$(".work_phone_class").change(function() {
$(".save_phone_class").trigger('click');
});
$(".work_phone_class_input").change(function() {
$(".save_phone_class").trigger('click');
});
Now I want to trigger the save button with the class when select field value is selected AND user completed typing on input box.
Update :
Html form is look like this. I think I have to use $(this) but not sure.
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1"></option>
</select>
<input type="text" class="work_phone_class_input">
I am no so clear about your requirement.... but i think this will help you
$(".work_phone_class,.work_phone_class_input").change(function() {
$(".work_phone_class_input").each(function(){
if($(this).val() == ""){
//// Validation goes here for input
return false;
}
})
$(".work_phone_class").each(function(){
if($(this).val() == undefined){
//// Validation goes here for input
return false;
}
//// trigger your save button click here
})
});
please let me know if it helps by marking it as an answer
You just have to add a test before send your ajax..
UPDATE
$(".save_phone_class").click(function(){
var allFilled = true;
$(".work_phone_class").each(function(){
if($(this).val()=="")
allFilled =false;
});
$(".work_phone_class_input").each(function(){
if($(this).val()=="")
allFilled =false;
});
if(allFilled)
{
//AJAX
}
});
$(".work_phone_class_save").click(function(){
var allFilled=true;
$(".work_phone_class_input").each(function(){
if($(this).val()=="")
allFilled=false;
});
$(".work_phone_class").each(function(){
if($(this).val()=="")
allFilled=false;
});
if(allFilled)
{
alert("Ajax sent");
}
else
alert("All input are not filled");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<select class="work_phone_class">
<option value=""></option>
<option value="1">1</option>
</select>
<input type="text" class="work_phone_class_input">
<button class="work_phone_class_save">Save</button>

change all select array name values in form except current select via jquery

I have n select array like this:
<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
.
.
.
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
user can choose all select as 'BOTTOM'
But I want user only can choose one 'TOP'
for example, If choose 'TOP',all of other select be 'BOTTOM'
I try write it via jQuery:
$("[name=upporder]").on('change',(function(e) {
e.preventDefault();
if(this.val() == 2)
// do not do anything
elseif(this.val() == 1)
//change all other 'select' value (with same name) to '2' except current 'select'
}
Try this:
$(".form-control").change(function(){ // handle click event of all selectbox
if($(this).val() == '1') { // check if TOP is selected
$(".form-control").val('2'); // first set all select box value to 2
$(this).val('1'); // set current selectbox to 1
}
});
you need to loop through lists by using .each()
$("select.form-control").on('change',function(e) {
e.preventDefault();
if($(this).val() == '2'){
// do not do anything
}else if($(this).val() == '1'){
//change all other 'select' value (with same name) to '2' except current 'select'
$("select.form-control").not($(this)).each(function(){
$(this).find('option[value="2"]').prop('selected', true);
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="upporder['1']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['2']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>
<select class="form-control" name="upporder['n']">
<option value="1">TOP</option>
<option value="2" selected>BOTTOM</option>
</select>

Compare select values and show alert if they match

I have 4 dropdowns from which you have to select an option.
What I am trying to do is show an alert if you chose the same option more than once. Its purpose is to keep the score for a game so a person shouldn't be able to play as 2.
At the moment the dropdown looks like this:
<select id="users_1" aria-labelledby="dropdownMenu1">
<option>Select player</option>
<?php foreach($users as $user) : ?>
<option value="<?=$user['id_user']?>"><?=$user['nume']?></option>
<?php endforeach; ?>
</select>
And what I've tried to do in JQuery is this:
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
And I also tried to compare them like this:
$("#users_2").change(function() {
if($(this).val() == $("#users_1").val()) {
alert($(this).val());
}
});
None seems to work and I have no clue why. I've checked and the actual values are taken from the view but the if clause cannot compare them apparently.
Thank you for any help! Much appreciated!
Get your values, don't set them
Change this…
$("#users_2").change(function() {
var a=$(this).val("#users_1");
var b=$(this).val("#users_2");
if(a == b) {
alert($(this).val());
}
});
…to this…
$("#users_2").change(function() {
var a = $("#users_1").val();
var b = $(this).val(); // equivalent to $("#users_2").val()
if(a === b) { // Use strict comparison operator as a best practice
alert(a + ' matches ' + b);
}
});
Make it dynamic
You can take it a step farther by listening to a set of elements and making your handler dynamic:
// Listen to set of all select elements.
$('select').on('change', function(e) {
// Serialize form values.
var vals = $('#select_player').serializeArray();
// Convert to simple array of just values.
vals = $.map(vals, function (val, i) {
return val.value;
});
// Remove current selection from array…
vals.splice(vals.indexOf($(this).val()), 1);
// …then check to see if it's value was already there.
if(vals.indexOf($(this).val()) !== -1) { // If value is found,
// …reset current select element to default option,
$(this).val('default');
// …and alert user with a relevant message.
alert('You cannot select this player more than once.');
};
});
label {
display: block;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="select_player" name="select_player">
<label>Player 1:
<select id="users_1" name="users_1">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 2:
<select id="users_2" name="users_2">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 3:
<select id="users_3" name="users_3">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
<label>Player 4:
<select id="users_4" name="users_4">
<option value="default" selected="selected" disabled>Select player</option>
<option value="uid001">John Doe</option>
<option value="uid002">Jane Doe</option>
<option value="uid003">Jerome Smith</option>
<option value="uid004">Janet O'Public</option>
</select>
</label>
</form>
I used the same class on all the dropdowns and then use only one event handler.
$('.dropdown').on('change', function (event) {
var selectedValue = $(event.currentTarget).val();
var matchedDropdowns = $('.dropdown').filter(function (index) {
return $(this).val() === selectedValue;
});
if (matchedDropdowns.length > 1) {
alert("Alert Alert!")
}
})
In the event handlers I can get the selected value, filter all the dropdowns that match that value and if I get more than 1 dropdown I will just show the alert.
You can check it on fiddle.

Categories

Resources