Changing divs depending on the selected select, checking the filled field - javascript

Can you please tell me how to change the values of divs depending on the select?
And then when the button is clicked, check whether the fields are filled with a certain selected div.
That is, if select is selected with a value of 1, a div with id 1 appears below, and when a button with id btn_save is pressed, it checks whether the field with id user1 is filled.
For select with value 2, a div with id 2 appears below, and when a button with id btn_save is pressed, it checks if the field with id user2 is filled.
Etc.
<select id="selects">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="1">
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="2">
<p>4 ...</p>
<input id="user2">
</div>
<div id="3">
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Подтвердить</button>

Here is a version using recommended event listeners
Note I use hidden on each div and I changed the ID from numeric. It is not recommended to have numeric IDs since they cannot be easily accessed by CSS
const divs = document.querySelectorAll("#boxes div");
const save = document.getElementById("btn_save")
document.getElementById("selects").addEventListener("change", function() {
const val = this.value;
divs.forEach(box => box.hidden = box.id !== `d${val}`)
})
save.addEventListener("click", () => {
const visible = [...divs].find(div => !div.hidden);
if (visible && visible.querySelector("input").value.trim() ==="") {
alert("Please enter a value")
}
})
<select id="selects">
<option selected value="">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="d1" hidden>
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="d2" hidden>
<p>2 ...</p>
<input id="user2">
</div>
<div id="d3" hidden>
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Подтвердить</button>

//Hide All Divs
$('#boxes').find('div').hide();
$('#btn_save').hide();
//Change div on select
$('#selects').on('change', function() {
$('input').removeClass('active');
$('input').val('');
$('#boxes').find('div').hide();
$('#d' + $(this).val()).show();
$('#btn_save').show();
$('#d' + $(this).val() + ' ' + 'input').addClass('active');
});
//button check input filed or not
$('#btn_save').on('click', function() {
if ($('#' + $('.active').attr('id')).val().trim() == '') {
alert('Please enter a value');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<select id="selects">
<option selected value="">Please select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<!-- DIVs -->
<div id="boxes">
<div id="d1">
<p>1 ...</p>
<p><input id="user1"></p>
</div>
<div id="d2">
<p>2 ...</p>
<input id="user2">
</div>
<div id="d3">
<p>3 ...</p>
<input id="user3">
</div>
</div>
<button type="button" id="btn_save">Save</button>

Related

Set labels of radio button group dynamically based on values selected in drop down lists

I have an html form with 4 form elements - 3 drop down lists and one group of radio buttons.
I want the label of the radio buttons to be set dynamically based on the values selected in the drop down lists.
Ex- The values selected in the drop down lists are q-tip, hold and h1 rspectively.
So, the labels in the radio button group (Direction) should be:
First radio button - q-tip hold h1.
Second radio button - h1 hold q-tip
This is the jsfiddle link : http://jsfiddle.net/coderr/yznf1qk3/22/
<div style="float:left;">
<h5>Object</h5>
<select name="object" id="object">
<option value="q-tip">q-tip</option>
<option value="o2">o2</option>
</select>
</div>
<div style="float:left;">
<h5>Action</h5>
<select name="action" id="action">
<option value="hold">hold</option>
<option value="a2">a2</option>
</select>
</div>
<div style="float:left;">
<h5>Person</h5>
<select name="humann" id="human">
<option value="h1">h1</option>
<option value="h2">h2</option>
</select>
</div>
<fieldset>
<legend>Direction</legend>
<input type="radio" name="direction" value="towards">q-tip hold h1<br>
<input type="radio" name="direction" value="away">h1 hold q-tip<br>
</fieldset>
You need to add some HTML to make it easier to access the text
$("#selects").on("change",function() { // any change of selects
const dirs = $(this).find("select").map(function() { return this.value }).get(); // get the values in an array
const $rads = $("[name=direction]"); // the radios
$rads.eq(0).next().text(dirs.join(" ")); // update the span after the radio - I wrapped in label too
dirs.reverse(); // reverse the array
$rads.eq(1).next().text(dirs.join(" ")); // add to the second radio span
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="selects">
<div style="float:left;">
<h5>Object</h5>
<select name="object" id="object">
<option value="q-tip">q-tip</option>
<option value="o2">o2</option>
</select>
</div>
<div style="float:left;">
<h5>Action</h5>
<select name="action" id="action">
<option value="hold">hold</option>
<option value="a2">a2</option>
</select>
</div>
<div style="float:left;">
<h5>Person</h5>
<select name="humann" id="human">
<option value="h1">h1</option>
<option value="h2">h2</option>
</select>
</div>
</div>
<fieldset>
<legend>Direction</legend>
<label><input type="radio" name="direction" value="towards"><span>q-tip hold h1</span></label><br>
<label><input type="radio" name="direction" value="away"><span>h1 hold q-tip</span></label><br>
</fieldset>

Jquery drop down with hidden form not working after cloning

I have a form with a drop-down with contains names of food items and another with an input field to allow the user to input price. beneath this, i have another drop down with class="IfNotAvailableSelectable" which contains 3 option, with values:0,1,2.
and I have a button called "addMore" to clone everything within the div with class="divContainer"
the following is what I want to achieve:
1.When the user clicks on the "addmore" button, it should clone everything within the div with class="divContainer" and append it to the div with class="addMoreContent". Of which I have been able to do successfully.
2.When the user selects the drop-down with class="IfNotAvailableSelectable" and value =0, it show div with class="thenBuy" , else it should hide it.
now the problem am facing is that, whenever i click the addmore button and select the drop down with option value 1 or 0 or 2, the original cloned div also changes with it,
so e,g: if i select value 1 ,i expect the div with class="thenBuy" to hide but when on the addmore button, and select the dropdown with value = 0, it show the div with class="thenBuy" in the 1st one too,while i don't want it to.
Please help,or if there;s a better solution to this.Will really appreciate.Thank you
HTML:
$(document).ready(function () {
//clone
var divContainer = $(".divContainer");
var addMoreContent = $(".addMoreContent");
var addMoreBtn = $(".addMoreBtn");
var removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var MainNav = $(this).val();
if (MainNav == 0) {
$(".thenBuy").show();
} else {
$(".thenBuy").hide();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>
With $(".thenBuy") you select all the elements with class name thenBuy you need to use .parent().find(".thenBuy")
To let the new .IfNotAvailableSelectable take change effect after cloned use .IfNotAvailableSelectable
$(document).ready(function () {
//clone
var divContainer = $(".divContainer"),
addMoreContent = $(".addMoreContent"),
addMoreBtn = $(".addMoreBtn"),
removeItem = $(".removeItem");
addMoreBtn.click(function () {
divContainer.clone(true).appendTo(addMoreContent);
addMoreContent.find(".IfNotAvailableSelectable").last().change(); //<<<<<<<<<< trigger the change event for the last/new IfNotAvailableSelectable
});
removeItem.click(function (e) {
$(this).closest('div').remove();
e.preventDefault();
});
//then buy functionO(when user selects "buy alternative")
$(document).on('change', '.IfNotAvailableSelectable', function () {
console.log($(this).val())
var ThisSelect = $(this); // define this
var MainNav = ThisSelect.val(); // get this val
if (MainNav == 0) {
ThisSelect.parent().find(".thenBuy").show(); // use .parent().find
} else {
ThisSelect.parent().find(".thenBuy").hide(); // use .parent().find
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- card body-->
<div class="card-body bg-white divContainer" >
<!-- delete button -->
<button type="button" class="close col-1 bg-white removeItem" >
<span>×</span>
</button>
<!-- items -->
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
<br>
<br>
<!-- price -->
<div >
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
<br>
<!-- if item is not available -->
<div style="font-size: medium;" >
<select class="custom-select text-capitalize IfNotAvailableSelectable">
<option value="0" >If item is not available</option>
<option value="1" >Remove it from my order </option>
<option value="2">Cancel entire order</option>
</select>
<br>
<!-- then buy -->
<div class="thenBuy" >
<div>
<span>Then Buy</span>
<select class=" custom-select text-capitalize">
<option >Waakye </option>
<option >Banku</option>
<option >Plain Rice</option>
</select>
</div>
<br>
<!-- price -->
<div >
<span>Price</span>
<input type="number" class="form-control" min="1" placeholder="starting price= GH¢1.00 " >
<!-- "min" above should be the value of the starting price of the selected item and placeholder strating price should be the value of the starting price of the selected item too-->
</div>
</div>
</div>
<!-- end of card body -->
</div>
<br>
<div class="addMoreContent" ></div>
<!-- onclick of add more,display the fiels here -->
<button type="button" class="float-right btn btn-outline-dark btn-sm addMoreBtn">Add More</button>
<br>

How do I get the checkbox state toggle between the two select boxes?

I have two select boxes which loads contacts and groups of contacts, how do I show one div at a time, switching between them by checking or unchecking the checkbox?
The code below show one at off state and show both two when checked instead of hiding the first one and showing the second one.
code snippet
$(document).ready(function () {
var checkbox = $('#checker');
var dependent = $('#dependent-box');
var dependent2 = $('#dependent-box2');
if (checkbox.attr('checked') !== undefined){
dependent.show();
dependent2.hide();
} else {
dependent2.show();
dependent.hide();
}
checkbox.change(function(e){
dependent.toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="checker" data-toggle="toggle">
<div id="dependent-box">
<div class="form-group" >
<select class="contact-multiple form-control" multiple="multiple" name="to_sms[]" id="toggle1" style="width: 98%;">
<option value="Hi">
Hi
</option>
</select>
</div>
</div>
<div id="dependent-box2">
<div class="form-group" >
<select class="contact-multiple form-control" multiple="multiple" name="to_sms[]" id="toggle1" style="width: 98%;">
<option value="Hi">
Hello
</option>
</select>
</div>
</div>
You are not toggling the second box in your change function.
checkbox.change(function(e){
dependent.toggle();
dependent2.toggle();
});
check if the checker is checked :
$(document).ready(function () {
var checkbox = $('#checker');
var dependent = $('#dependent-box');
var dependent2 = $('#dependent-box2');
dependent2.hide();
checkbox.change(function(e){
if(this.checked){
dependent.hide();
dependent2.show();
}else
{
dependent.show();
dependent2.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="checker" data-toggle="toggle">
<div id="dependent-box">
<div class="form-group" >
<select class="contact-multiple form-control" multiple="multiple" name="to_sms[]" id="toggle1" style="width: 98%;">
<option value="Hi">
Hi
</option>
</select>
</div>
</div>
<div id="dependent-box2">
<div class="form-group" >
<select class="contact-multiple form-control" multiple="multiple" name="to_sms[]" id="toggle1" style="width: 98%;">
<option value="Hi">
Hello
</option>
</select>
</div>
</div>

html with several drop downs each with its own show/hide textarea

I have html with several drop downs. Depending on the each selection a textarea shows for description. Right now I have a show and hide in javascript for each question. Is there a way to concise this so that I dont have to write show/hide for each question. What I mean is, Is there a way that my javascript will be more concise?
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Food Selection</title>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#spicyFoodField').on('change', function() {
if (this.value == 'spicyFoodDesc') {
$("#spicyFoodDesc").show();
} else {
$("#spicyFoodDesc").hide();
}
});
});
$(document).ready(function() {
$('#sweetFoodField').on('change', function() {
if (this.value == 'sweetFoodDesc') {
$("#sweetFoodDesc").show();
} else {
$("#sweetFoodDesc").hide();
}
});
});
$(document).ready(function() {
$('#blandFoodField').on('change', function() {
if (this.value == 'blandFoodDesc') {
$("#blandFoodDesc").show();
} else {
$("#blandFoodDesc").hide();
}
});
});
</script>
</head>
<body>
<div class="w3-row-padding" id="spicyFood">
<div class="w3-third">
<label class="w3-text-green" for="spicyFoodLabel"><b>Do you like spicy food?</b></label>
<p>
<select id="spicyFoodField">
<option value="" disabled selected>Select...</option>
<option value="spicyFoodDesc">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" id="spicyFoodDesc" name="spicyFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>
<div class="w3-row-padding" id="sweetFood">
<div class="w3-third">
<label class="w3-text-green" for="spicyFoodLabel"><b>Do you like sweet food?</b></label>
<p>
<select id="sweetFoodField">
<option value="" disabled selected>Select...</option>
<option value="sweetFoodDesc">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" id="sweetFoodDesc" name="sweetFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>
<div class="w3-row-padding" id="sweetFood">
<div class="w3-third">
<label class="w3-text-green" for="blandFoodLabel"><b>Do you like sweet food?</b></label>
<p>
<select id="blandFoodField">
<option value="" disabled selected>Select...</option>
<option value="blandFoodDesc">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" id="blandFoodDesc" name="blandFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>
</body>
</html>
There is certainly a way to achieve what you're after, and my preference is to use a combination of one event listener, and data attributes.
The idea is that you apply one event that fires on the change of any select, rather than having one for each.
$("select").on("change", ...);
To find out exactly which one changed, you can use $(this). Therefore, $(this).val() will tell us if the dropdown is switching to "yes" or "no".
var selectedValue = $(this).val();
We can add the parameter data-for-id to each description, and set it to the ID of the associated select. For example, if you have a select with an id of mySelect, the textarea would have data-for-id="mySelect".
<select id="spicyFoodField">
....
</select>
<textarea data-for-id="spicyFoodField" />
Now we've created a link between our select and its textarea. Let's implement that in our jQuery code, so that when the select gets changed, it knows what textarea to look for:
//Set the associated text area to whatever textarea has
//the same data-for-id as the changing select list
var $associatedTextarea = $("textarea[data-for-id=" + $(this).attr("id") + "]");
Finally, we can implement our logic to hide the area, or show the area:
if (selectedValue == "yes") {
$associatedTextarea.show();
} else {
$associatedTextarea.hide();
}
Now, any time we want to add a new Select / Textarea, all we have to do is put data-for-id="associated-select-id" on the textarea, and the code will handle the rest.
Complete example:
$(document).ready(function() {
$("select").on("change", function() { //When a select changes
var selectedValue = $(this).val(); //Check its new value
//Get associated textarea
var $associatedTextarea = $("textarea[data-for-id=" + $(this).attr("id") + "]");
if (selectedValue == "yes") {
$associatedTextarea.show();
} else {
$associatedTextarea.hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/3/w3.css">
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<div class="w3-row-padding" id="spicyFood">
<div class="w3-third">
<label class="w3-text-green" for="spicyFoodLabel"><b>Do you like spicy food?</b></label>
<p>
<select id="spicyFoodField">
<option value="" disabled selected>Select...</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" data-for-id="spicyFoodField" id="spicyFoodDesc" name="spicyFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>
<div class="w3-row-padding" id="sweetFood">
<div class="w3-third">
<label class="w3-text-green" for="spicyFoodLabel"><b>Do you like sweet food?</b></label>
<p>
<select id="sweetFoodField">
<option value="" disabled selected>Select...</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" data-for-id="sweetFoodField" id="sweetFoodDesc" name="sweetFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>
<div class="w3-row-padding" id="sweetFood">
<div class="w3-third">
<label class="w3-text-green" for="blandFoodLabel"><b>Do you like sweet food?</b></label>
<p>
<select id="blandFoodField">
<option value="" disabled selected>Select...</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</p>
</div>
<div class="w3-twothird">
<p>
<textarea class="w3-hover-light-blue" data-for-id="blandFoodField" id="blandFoodDesc" name="blandFoodDesc" rows="2" hidden> </textarea>
</p>
</div>
</div>

How to show an entire div on select

I need some help displaying a div with a form inside of it whenever someone selects a certain option from a tag. My code is this:
<script type="text/javascript">
$(function() {
$('#contactOptionSelect').change(function() {
$('.emailForm').hide();
$('#' + $(this).val()).show();
});
});
</script>
<div class="contactSelect" id="contactOptionSelect">
<label for="selectContact">Contact us: </label>
<select name="selectContact" class="selectContactType" style="width: 150px;"/>
<option class="opt" value="">Please select</option>
<option class="opt" id="helpOpt" value="">Help and Support</option>
<option class="opt" id="emailOpt" value="">Email</option>
<option class="opt" id="visitOpt" value="">Visit us!</option>
<option class="opt" id="phoneOpt" value="">Phone</option>
</select>
</div>
<div class="emailForm" id="emailFormId">
<form id="contactUsForm" method="post" action="">
<div class="formSubject">
<label for="inputSubject">Subject</label>
<input type="text" width="50px" id="inputSubject" />
</div>
<div class="formBody">
<label for="inputBody">Email</label>
<textarea rows="15" cols="50" id="inputBody"></textarea>
</div>
<div class="formSubmit">
<input type="submit" id="inputSubmit" value="Send!"/>
</div>
</form>
</div>
And I want to display the last form when the email option is selected. I kinda want it to work like this: http://www.apple.com/privacy/contact/ High standards I know but whatever haha Thanks in advance for any help!
Are you looking for something like this? http://jsbin.com/okakuy/edit#javascript,html
Whenever the select option is changed, we hide whichever div is visible, and show whichever div has the current select value as its id attribute.
$("#parts").on("change", function(o){
$(".panels")
.find("> div:visible")
.slideUp()
.end()
.find("#" + o.target.value)
.slideDown();
});
Coupled with this markup:
<select id="parts">
<option>foo1</option>
<option>foo2</option>
<option>foo3</option>
</select>
<div class="panels">
<div id="foo1">This is foo1</div>
<div id="foo2">This is foo2</div>
<div id="foo3">This is foo3</div>
</div>

Categories

Resources