Here is my html that will loaded with ajax call.
<select id="choice-id" name="choice_name">
<option value="2">2</option>
<option value="3" selected="">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div style="display: block;" id="select" class="other">
<input id="other-0" name="other_0" type="text" value="abc">
<input id="other-1" name="other_1" type="text" value="pqr">
<input id="other-2" name="other_2" type="text" value="rst">
</div>
here is my jquery for changing input field corresponding to option select. if i select option with value '6' it will generate 6 input field without any values.
$(document).on('change','#choice-id',function() {
var choicesizeSelected = $("#choice-id :selected").val();
$('.other').empty();
for(var i=0; i<choicesizeSelected; i++) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
this code is working perfectly. but if i select again default option 3, i want return default 3 input field with same values.
thanks in advance.
What you are doing is emptying the whole .other div.
Instead, compare if the number of inputs is bigger or smaller than selected.
If the selected number is bigger: add fields
If the selected number is smaller: remove fields
If the selected number is the same: do nothing
$(function() {
$('#choice-id').on('change', function() {
var newNum = $(this).find(':selected').val();
var oldNum = $('.other input').length;
if( oldNum > newNum ) {
var x = parseInt(newNum)+1;
$('.other input:nth-child(n+'+x+')').remove();
}
else if( oldNum < newNum ) {
for( var i=oldNum; i<newNum; i++ ) {
$('.other').append("<input id='other-"+i+"' type='text' name='other_"+i+"'></input>");
}
}
});
});
DEMO
Related
I have a dropdown menu with products similiar like this
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananes</option>
<option value="3" >Apples</option>
</select>
I need to remove options by its value. How to do that ?
Pure JavaScript please.
EDIT : I know that I need to use element.removeChild(child) method. But how to reference child by its value. Thats my point.
EDIT 2 : I use the script of zdrohn below and it works. Because I have several fruits dropdowns with the same collection I need to iterate trough all dropdowns and delete it from all dropdowns. This is my code now :
<script type='text/javascript'>
var id = 3;
var el= document.getElementsByClassName("fruits");
for (i=0;i<el.length;i++) {
for(var n = 0; n < el[i].length; n++) {
if(el[i][n].value == id) {
el[i][n].remove();
}
}
</script>
Though it works I wonder about that I do not need to use the parent.removeChild() method. How comes ?
P.S. I wonder that peole vote this question down. As the response shows their are several solutions. Though not all are sufficiantly explained.
Here is a snippet to play with.
The code removes the option with value = 3
window.onload = function() {
var optionToDelete = document.querySelector("select.fruits > option[value='3']");
optionToDelete.parentNode.removeChild(optionToDelete);
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
EDIT: Based on the updated question - I have several fruits drop-downs.
We could make use of querySelectorAll to select all matching elements and forEach to apply the desired logic on each element in the selected list.
window.onload = function() {
var optionsToDelete = document.querySelectorAll("select.fruits > option[value='3']");
optionsToDelete.forEach(function(element, index, array) {
element.parentNode.removeChild(element);
});
}
<select class="fruits">
<option value="1">Oranges</option>
<option value="2">Bananes</option>
<option value="3">Apples</option>
</select>
<select class="fruits">
<option value="1">Seville oranges</option>
<option value="2">Burro Bananes</option>
<option value="3">Baldwin Apples</option>
</select>
<select class="fruits">
<option value="1">Bergamot oranges</option>
<option value="2">Red Bananes</option>
<option value="3">Gravenstein Apples</option>
</select>
<select class="fruits" >
<option value="1" >Oranges</option>
<option value="2" >Bananas</option>
<option value="3" >Apples</option>
</select>
<script type='text/javascript'>
var valueToRemove = 1;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
</script>
Edit:
<select class="fruits" >
<option value="1">Oranges</option>
<option value="2">Bananas</option>
<option value="3">Apples</option>
</select>
<br>
<label>Input value to delete</label><input type='text' id='delete_value'>
<button onclick='remove(document.getElementById("delete_value").value)'>Delete</button>
<script type='text/javascript'>
function remove(item) {
var valueToRemove = item;
var select = document.getElementsByClassName('fruits');
for(var i = 0; i < select[0].length; i++) {
if(select[0][i].value == valueToRemove) {
select[0][i].remove();
}
}
}
</script>
You can select the desired option by using document.querySelector() and a selector of this form
A more complete list of selectors can be found here
Example
var element = document.evaluate( '//option[#value="1"]' ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;
element.parentNode.removeChild(element)
I want to make dynamic form field. for instance, depends on the selection of form field, I want to show hidden field or hide showed block.
For example, if I selected first field with 'high school', then show 'Marital Status' field. This field is hidden by default.
See the example code here
Thank you so much!!
Here is HTML
<!-- fieldsets -->
<fieldset>
<h2 class="fs-title">Check your eligibility</h2>
<h3 class="fs-subtitle">About yourself</h3>
<label for="educationLevel" tabindex="1">Education:<select name="educationLevel" class="pie" id="educationLevel" onchange="myfunction();">
<option value="0">Select an option</option>
<option value="1">High School</option>
<option value="2">College</option>
<option value="3">Grad School</option>
</select></label>
<label for="quiz-applicantCountry" tabindex="1" id="yourself">YOUR COUNTRY OF BIRTH:<select name="applicantCountry" id="your-applicantCountry" class="pie" onchange="myfunction();">
<option value="0">Select a Country</option>
<option value="54">Afghanistan</option>
<option value="93">Albania</option>
...
<option value="52">Zambia</option>
<option value="53">Zimbabwe</option>
</select></label>
<label for="maritalStatus" tabindex="2" id="marital">Marital Status:<select name="maritalStatus" class="pie" id="maritalStatus" onchange="myfunction();">
<option value="0">select</option>
<option value="1">YES</option>
<option value="2">NO</option>
</select></label>
<label for="quiz-applicantCountry" tabindex="1" id="spouse">YOUR SPOUSE COUNTRY OF BIRTH:<select name="applicantCountry" id="spouse-applicantCountry" class="pie" onchange="myfunction();">
<option value="0">Select a Country</option>
<option value="54">Afghanistan</option>
...
<option value="52">Zambia</option>
<option value="53">Zimbabwe</option>
</select></label>
<input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
</form>
Here is Javascript
function myfunction(){
var birthSelectedCountry = $("select#your-applicantCountry option:selected").val();
// console.log(birthSelectedCountry);
var country = "-" + birthSelectedCountry + "-";
var eligibleCountries = "-61-65-81-86-82-91-266-223-95-102-175-104-106-112-120-140-146-156-163-221-190-177-181-183-187-261-262-189-194-56-182-38-279-287-267-115-123-280-288-286-137-281-289-282-283-149-270-284-285-1000-";
var birthSpouseSelectedCountry = $("select#your-applicantCountry option:selected").val();
// console.log(birthSpouseSelectedCountry);
var spouseCountry = "-" + birthSpouseSelectedCountry + "-";
var eligibleSpouseCountries = "-61-65-81-86-82-91-266-223-95-102-175-104-106-112-120-140-146-156-163-221-190-177-181-183-187-261-262-189-194-56-182-38-279-287-267-115-123-280-288-286-137-281-289-282-283-149-270-284-285-1000-";
var maritalStatus = $("select#maritalStatus option:selected").val();
// console.log(maritalStatus);
var marital = "-" + maritalStatus + "-";
var eligibleMarital = "-1-2-";
var educationLevel = $("#educationLevel option:selected").val();
var education = "-" + educationLevel + "-";
var eligibleEducationLevel = "-2-3-";
console.log(education);
console.log(marital);
console.log(country);
console.log(eligibleEducationLevel.indexOf(education));
console.log(eligibleMarital.indexOf(marital));
console.log(eligibleCountries.indexOf(country));
if( eligibleEducationLevel.indexOf(education) < 0 && eligibleCountries.indexOf(country) < 0 ) {
console.log("Are you married?");
// $('#marital').fadeIn();
$('#marital').css('display', "block");
}
Try this:
JAVASCRIPT
if ($("#educationLevel").val() == "1"){
$("#maritalStatus").show();
} else {
// Do something else..
}
This is if I understood the question correctly.
In your document.ready() event hide all the controls by referencing them by their ids. The document.ready() function is used to initialize the entire behaviour of the entire page.
$(document.ready(function(){
//hide the maritalStatus dropdown initially at pageload.
$('#maritalStatus').hide();
$('#spouse-applicantCountry').hide();
$('#maritalStatus').val(0);
$('#spouse-applicantCountry').val(0);
//This the onchange event of the select
$('#educationLevel').on('change', function() {
$('#maritalStatus').show();
//Put your conditions here
if($('#maritalStatus').val() == "1"){
$('#spouse-applicantCountry').show();
}
});
}));
The dropdown onChange functions wont work properly as expected as the select control is often rendered before the function is defined.
Hope this helps !
Cheers !
I have two select options for adults and children in my form:
<select name="BKG_Adult">
<option value="1" data-price="1000">1</option>
<option value="2" data-price="2000">2</option>
<option value="3" data-price="3000">3</option>
<option value="4" data-price="4000">4</option>
</select>
<select name="BKG_Child">
<option value="0" data-price="0">0</option>
<option value="1" data-price="500">1</option>
<option value="2" data-price="1000">2</option>
<option value="3" data-price="1500">3</option>
</select>
<input type="hidden" id="dynamic_availability" name="dynamic_availability" value="4">
The hidden field dynamic availability is populated by an external web service on page load to give the total amount of seats available on a tour. The options are also populated on page load.
The main rule of the form is that at least one adult must travel on the tour. The remaining seats can then be made up of a combination of children and adults.
If 2 adults are selected, I need to reduce the amount of options in the child select to ensure that the user cannot select over 4 people in total. Equally, if 2 children are selected in the child select I must restrict the values in the adult select but still ensure that at least one adult is selected.
Essentially this will use the onchange event of the child and adult select fields but the complexity is filtering the options based upon the rules defined above. Of course, if the user were to reduce the number of options selected in one field, the number of options should increase in the other field so that the user can still select a maximum of 4.
Does anyone know of an example of such functionality or how this can be implemented in vanilla javascript or jquery?
$(function() {
var max = $("#dynamic_availability").val(),
$adult = $("#adult"),
$child = $("#child");
fillCmb($adult, 1, max);
fillCmb($child, 0, max - 1);
$adult.on("change", function() {
var cant = $(this).val();
fillCmb($child, 0, max - cant);
});
$child.on("change", function() {
var cant = $(this).val();
fillCmb($adult, 1, max - cant);
});
function fillCmb($cmb, min, max) {
var val = $cmb.val();
$cmb.empty();
for (var i = min; i <= max; i++)
$cmb.append("<option value=\"" + i + "\">" + i + "</option>");
if (val)
$cmb.val(val);
}
});
http://jsfiddle.net/paska/9ac1ta7u/2/
function changeSelect(element, otherSelectValue){
var options = element.find(option);
for(x=0; options.length; x++){
if((options[x].value() + value) > 4){
options[x].remove();
}
}
}
$('#adult', '#child').on('change', function(){
if(this.attr('id') === 'adult'){
changeSelect($('#child'), this.val());
}else{
changeSelect($('#adult'), this.val());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="adult" name="BKG_Adult">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="child" name="BKG_Child">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
I hope I can explain this well. Note the attached image below. Each has a classname of "classtime" and contains a list of available schedules for a class.
As you can see in the "instructions" in the image, I need to validate that a user doesn't select classes on back-to-back days. I'm not sure how to do this in jQuery; I'm fairly sure it can be done, and probably easily, but I don't know how.
So the plan is to act on the change() event of a given drop-down, and then look at the value of the select before and the select after, and if the value is not 0, complain to the user and reset the value of the current drop-down to 0.
Thanks!
This is one way with disables.
$('select').change(function(){
var hasVal = $(this).val() != 0;
var index = $('select').index(this);
var total = $('select').length;
//before select
if((index-1) >= 0){
var disableBefore = hasVal;
// check incase 2 before has a value
if(!disableBefore && ((index-2) > 0)){
disableBefore = $('select:eq(' + (index-2) + ')').val() != 0;
}
$('select:eq(' + (index-1) + ')').prop('disabled', disableBefore);
}
//after select
if((index+1) < total){
var disableAfter = hasVal;
// check incase 2 after has a value
if(!disableAfter && ((index+2) < total)){
disableAfter = $('select:eq(' + (index+2) + ')').val() != 0;
}
$('select:eq(' + (index+1) + ')').prop('disabled', disableAfter);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<select>
<option value="0">a</option>
<option value="1">aa</option>
</select>
</div>
<div>
<select>
<option value="0">b</option>
<option value="1">bb</option>
</select>
</div>
<div>
<select>
<option value="0">c</option>
<option value="1">cc</option>
</select>
</div>
<div>
<select>
<option value="0">d</option>
<option value="1">dd</option>
</select>
</div>
<div>
<select>
<option value="0">e</option>
<option value="1">ee</option>
</select>
</div>
<div>
<select>
<option value="0">f</option>
<option value="1">ff</option>
</select>
</div>
<div>
<select>
<option value="0">g</option>
<option value="1">gg</option>
</select>
</div>
I have these conditional drop lists behaving on screen as expected, but I cannot get the selected values from the drop downs to output in the HTML form (I can if I don't include the javascript). Only the text inputs are outputing as per the xml result below (Company & Add1). I want the xml to contain the Location from the first drop down, and the selected city from the conditional 2nd drop down.
<body>
<form action="http://TESTPLANETPRESS:8080/ObtainQuote" method="GET" >
<fieldset>
<legend>Location</legend>
<select id="country" class="source" onchange="updateSelectTarget()">
<option value="England">England</option>
<option value="France">France</option>
<option value="Germany">Germany</option>
</select>
<select id="England">
<option value="Birmingham">Birmingham</option>
<option value="Liverpool">Liverpool</option>
<option value="London">London</option>
</select>
<select id="France" class="hidden">
<option value="Lyon">Lyon</option>
<option value="Marseille">Marseille</option>
<option value="Paris">Paris</option>
</select>
<select id="Germany" class="hidden">
<option value="Berlin">Berlin</option>
<option value="Hamburg">Hamburg</option>
<option value="Munich">Munich</option>
</select>
<label for="Company">Company:</label><input type="text" name="Company" value="Google">
<label for="Add1">Add1:</label><input type="text" name="Add1" value="1 Nowhere Street">
</fieldset>
<input type="submit" value="Submit">
</form>
<script>
function updateSelectTarget () {
var id = this.options[this.selectedIndex].value;
var targets = this.parentNode.getElementsByTagName("select");
var len = targets.length;
for (var i = len - 1; i > 0; --i) {
if (targets[i].id == id) {
targets[i].style.display = "block";
}
else {
targets[i].style.display = "none";
}
}
}
function initChangeHandler () {
var el = document.getElementById("country");
el.onchange = updateSelectTarget;
el.onchange();
}
window.onload = initChangeHandler;
</script>
</body>
Current XML result, (Does not include the results from the two drop downs).
<?xml version="1.0"?>
-<request type="GET">
<paths count="0"/>
-<values count="2">
<Company>Google</Company>
<Add1>1 Nowhere Street</Add1>
</values>
Do you want the value attribute or the text? Based on Get selected value in dropdown list using JavaScript? (similar to the first part), .value should work for the value attribute and .text for the text that is selected.
Also, please make two different questions instead of one question with 2 questions nested inside.