Properly append multiple element <div> with proper index - javascript

I have a multi-element and dependent div that asks the user to first pick a state. Once the state is picked, then it will provide users with the appropriate city in the state.
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
jQuery:
$(document).ready(function() {
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a city</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).eq(current).val() == 'California') {
$(".city").eq(current).html("<option>San Francisco</option><option>Los Angeles</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(".city").eq(current).html("<option>New York City</option><option>Albany</option>");
$(".city option:first").eq(current).attr('selected', 'selected');
$(".city").eq(current).attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
if (maxAppend >= 4) return;
var additional = $(".trip").html();
$(".trip").after(additional);
maxAppend++;
});
});
I want to allow the users to add the class "trip" up to four times. When I use append() or after() as show above. The index of the newly added item rests to 1, which cause the selected in the first trip to reset because it has the same index. What is the proper and elegant way of implementing this?
here is the link to the jsfiddle: https://jsfiddle.net/L2bfmo69/

Here you go with the solution https://jsfiddle.net/L2bfmo69/5/
$(document).ready(function() {
var additional = $(".trip").html();
$("#result").hide();
$("form").on("change", "select", function(){
var current = $(this).index();
if($(this).eq(current).val() == 'Z') {
$(".city").eq(current).html("<option>Select a fare</option>");
$(".city").eq(current).attr('disabled', true);
}
else {
if($(this).val() == 'California') {
$(this).next().html("<option>San Francisco</option><option>Los Angeles</option>");
$(this).next().attr('disabled', false);
}
if($(this).eq(current).val() == 'New York') {
$(this).next().html("<option>New York City</option><option>Albany</option>");
$(this).next().attr('disabled', false);
}
}
});
var maxAppend = 0;
$("#add").click(function() {
$(".summary").append('<div class="trip">' + additional + "</div>");
if ($('.summary').children().length >= 4) {
$('#add').prop('disabled', true);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post">
<div class="summary">
<div class="trip">
<select name="State" class="state">
<option selected disabled>Choose a State</option>
<option>California</option>
<option>New York</option>
</select>
<select name="City" class="city" disabled="true">
<option value="Z">Select a city</option>
</select>
<br><br>
</div>
</div>
<div id="nexttrip"></div>
<button type="button" id="add">Add another trip</button>
<br><br>
<input type="submit">
</form>
After 4 insert by the user I have disabled the add button.

Related

How to make this multidrop form to array

I have a multidrop form at this fiddle : Here's a link! . at this form only can add multidrop 3 times, i want to make always add this multidrop, and how to save the array data into sql
<div id="Yes1">
<label for="name" >Name</label>
<input type="text" id="name1" name="name1">
<br><br>
<label for="multiDrop" >Multi Drop</label>
<select name="multiDrop1" id="multiDrop1">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
Check here to add and remove your elements as per your requirement.
You can remove only that block which you selected No for.
$(document).ready(function() {
$(document).on("change", ".multidrop", function() {
if ($(this).val() == 'Y') {
$clone = $(this).closest(".Yes").clone();
var num = parseInt($(".Yes:last").attr("data-index")) + 1;
$clone.attr("data-index", num);
$clone.attr("id", $clone.attr("id").replace(/\d+/, num));
$clone.find("input,select").each(function() {
var name = ($(this).attr("name")).replace(/\d+/, num);
var id = ($(this).attr("id")).replace(/\d+/, num);
$(this).attr("name", name);
$(this).attr("id", id);
});
$clone.insertAfter(".Yes:last"); //Add field html
} else if ($(this).val() == "N" && $(".Yes").length > 1) {
$(this).closest(".Yes").remove();
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="Yes1" class="Yes" data-index="1">
<label for="name">Name</label>
<input type="text" id="name1" name="name1" class="name">
<label for="multiDrop">Multi Drop</label>
<select name="multiDrop1" id="multiDrop1" class="multidrop">
<option value="">Select Option</option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
<br><br>
</div>
I would recommend to use following approach:
get your repetitive block HTML into a variable;
listen for changes of drop down (using event delegation, selecting by class rather than id);
modify necessary attributes (names, id's, etc) based on global counter to distinguish those dynamic blocks;
const block = `
<div class="block">
<div class="yes">
<label>Name</label>
<input type="text" class="name"></input>
<label>Multi Drop</label>
<select class="multiDrop">
<option value=""></option>
<option value="Y">YES</option>
<option value="N">NO</option>
</select>
</div>
</div>
`;
const addAnotherBlock = () => {
$('#wrapper').append(block);
$('.name:last').attr('name',i++);
};
var i = 0;
$(document).ready(() => addAnotherBlock());
$('#wrapper').on('change', '.multiDrop', function(){
if($(this).val() == 'Y') addAnotherBlock();
else if($(this).val() == 'N' && $('.block').length > 1 && !$(this).closest('.block').is('.block:last')){
$(this).closest('.block').remove();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="wrapper"></div>

I Retained Select Option Value on First Dropdown but not Second or Third

I have 3 form select drop downs and have successfully retained the first select value after page loads, but am unable to get the second and third select values to be retained.
I'm using JavaScript and Jquery only for this.
I've tried over and over and finally got to bring my code here to see if someone more advanced can point out what I'm not doing correctly.
<form id="form">
<select id="select0" type="text">
<option type="text" value="" >make</option>
<option type="text" value="ford" >ford</option>
</select>
<select id="select1" type="text">
<option type="text" value="" >model</option>
<option type="text" value="mustang" >mustang</option>
</select>
<select id="select2" type="text">
<option type="text" value="">year</option>
<option type="text" value="1967" >1967</option>
</select>
<input type="submit" value="go">
</form>the
// JavaScript
var storeMake = sessionStorage.getItem("themake");
var storeModel = sessionStorage.getItem("themodel");
var storeYear = sessionStorage.getItem("theyear");
var make = $("#form #select0");
var model = $("#form #select1");
var year = $("#form #select2");
if(storeMake != undefined || storeMake != null){
make.find(":selected").removeAttr("selected");
make.find("option").each(function () {
if ($(this).val() == storeMake) {
$(this).attr("selected", true);
}
});
}
if(storeModel != undefined || storeModel != null){
model.find(":selected").removeAttr("selected");
model.find("option").each(function () {
if ($(this).val() == storeModel) {
$(this).attr("selected", true);
}
});
}
if(storeYear != undefined || storeYear != null){
year.find(":selected").removeAttr("selected");
year.find("option").each(function () {
if ($(this).val() == storeYear) {
$(this).attr("selected", true);
}
});
}
make.change(function () {
sessionStorage.setItem("themake", make.val());
});
model.change(function () {
sessionStorage.setItem("themodel", model.val());
});
year.change(function () {
sessionStorage.setItem("theyear", year.val());
});
The jQuery .val() method can be used to set the value of a select. This will replace each if statement.
Try the code below. The snippet will not work in Stack Overflow because sessionStorage is disabled.
var storeMake = sessionStorage.getItem("themake"),
storeModel = sessionStorage.getItem("themodel"),
storeYear = sessionStorage.getItem("theyear");
$("#select0").val(storeMake).change(function () {
sessionStorage.setItem("themake", $(this).val());
});
$("#select1").val(storeModel).change(function () {
sessionStorage.setItem("themodel", $(this).val());
});
$("#select2").val(storeYear).change(function () {
sessionStorage.setItem("theyear", $(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
<select id="select0">
<option value="">make</option>
<option value="ford">ford</option>
</select>
<select id="select1">
<option value="">model</option>
<option value="mustang">mustang</option>
</select>
<select id="select2">
<option value="">year</option>
<option value="1967">1967</option>
</select>
<input type="submit" value="go">
</form>
A few added notes:
The type attribute is not needed on select or option elements.
$("#form #select0") can updated to $("#select0") since the id will be unique. Same with select1 and select2.

show hide div based on select option value jQuery

I have a select list with value 0,1,2,3,4,5,6,7 .On select with value 0 and 1 I want to show a div, but on select with value 2,3,4,5,6,7 I want to hide that div.The code I have right now is below
HTML
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
jQuery
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function(){
$('.rel_status').change(function(){
if($('.rel_status').val() == '2','3','4','5','6','7') {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
The code actually works when I put
.val() == '2')
instead of
.val() == '2','3','4','5','6','7')
But then I cant show the div for other values
You can do it like this if ($.inArray($(this).val(), "2,3,4,5,6,7") == -1) {
Demo
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function() {
$('.rel_status').change(function() {
if ($.inArray($(this).val(), "2,3,4,5,6,7") == -1) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
use this it will works
$('.rel_status').change(function(){
if($('.rel_status').val() < 2) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
//hide partner search form
$('.rel_part').hide();
//Search Relationship partner
$(document).ready(function(){
$('.rel_status').change(function(){
if($('.rel_status').val() < 2) {
$('.rel_part').show();
} else {
$('.rel_part').hide();
}
});
});
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select class="rel_status">
<option value="0">---</option>
<option value="1">Single</option>
<option value="2">In a relationship</option>
<option value="3">Engaged</option>
<option value="4">Married</option>
<option value="5">Separated</option>
<option value="6">Divorced</option>
<option value="7">Widowed</option>
</select>
<div class="rel_part">
<input type="text" name="part_name" placeholder="Search">
</div>
That's not a valid way of comparing one value to many others.
if($('.rel_status').val() == '2','3','4','5','6','7')
Use a logic OR Operator instead:
if($('.rel_status').val() == '0' || $('.rel_status').val() = '1') {
$('.rel_part').hide();
} else {
$('.rel_part').show();
}
Notice, that I switched the cases in the if clause so it's less code to write.
The problem is this is not a valid way to use , in Javascript, because you will end up validating if($('.rel_status').val() == '7') { instead.
You can change the code into this
if($.inArray($('.rel_status').val(), ['2','3','4','5','6','7']) != -1) {
and it should work.
Hope it helps!

How to get options element by id and output text

Could someone help me with this little javascript. I want the rersult to show in NA only when option value 2 is selected. I want 11" to show will show. Need a simple script to output custom text based on value text. I do know i have value="2" listed twice. I cannot use the value field.
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if(document.getElementById("test").value == "11") {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>
You can check the text of the option like
function myFunction() {
var el = document.getElementById("sizing-change");
if (el.options[el.selectedIndex].text.trim() == '11"') {
document.getElementById("finalsize").innerHTML = "Size: 11";
} else {
document.getElementById("finalsize").innerHTML = "NA";
}
}
<select id="sizing-change" onchange="myFunction()">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>
If you can alter the value field of option to different values(which you should) then you can try this:
<select id="sizing-change" onchange="myFunction()">
<option value="12">12</option>
<option value="11" id="test">11</option>
</select>
<div class="sizefinal">Suggested Size: <span id="finalsize">NA</span>
</div>
<script>
function myFunction() {
if (document.getElementById("sizing-change").value == 11) {
document.getElementById("finalsize").innerHTML = "Size: 11";
}
}
</script>
Demo: http://jsfiddle.net/GCu2D/784/
var finalsize = document.querySelector('#finalsize');
var sizingChange = document.querySelector('#sizing-change')
var testOption = sizingChange.querySelector('#test');
myFunction(sizingChange);
function myFunction(element) {
var checked = element.querySelector(':checked');
if (checked == testOption) {
finalsize.innerHTML = "Size: " + element.querySelector(':checked').text;
} else {
finalsize.innerHTML = 'NA';
}
}
<select id="sizing-change" onchange="myFunction(this)">
<option value="2">12"</option>
<option value="2" id="test">11"</option>
</select>
<div class="sizefinal">
Suggested Size: <span id="finalsize">NA</span>
</div>

How to get select array empty

The name of my select option property is populated dynamically.
On submit my form I need to know if all my forams selects filled ...
How can I do this?
I would also like to take the mouse cursor to the select that was not filled.
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#teste").click(function () {
a = $("select[name='sel[]'] option:selected").length;
alert(a);
});
});
</script>
<title>
</title>
</head>
<form>
<select name="sel[0]">
<option value="teste"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<br />
<br />
<br />
<select name="sel[1]">
<option value="teste"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
... Many others
<input type="button" id="teste" value="TESTAR">
</form>
</html>
Give your default option a value of -1 and provide a common class name for these options(Which is efficient that attribute starts with selector).
Try:
HTML:
<form>
<select name="sel[0]" class="sel">
<option value="-1"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<br />
<br />
<br />
<select name="sel[1]" class="sel">
<option value="-1"></option>
<option value="teste">1234</option>
<option value="teste">1234</option>
<option value="teste">1234</option>
</select>
<input type="button" id="teste" value="TESTAR">
JS:
$(document).ready(function () {
$("#teste").click(function () {
$(".sel").each(function () {
if (this.value == -1) { //If you are not providing value check for this.selectedIndex == 0
$(this).focus(); //set the focus
return false; //and break out of the loop
}
});
});
});
Fiddle
You have to set the variable like this var a;.
There is no element with select[name='sel[]'], you have a number inside of it, you could use name*= or name^= to say name contains or name starts with sel respectively
JSFIDDLE DEMO
$("#teste").click(function () {
var a = $("select[name^='sel'] option:selected");
var count = 0;
$.each(a, function () {
if ($(this).text().length) {
count++;
}
});
alert(count);
});
Select acts like the usual input when submitting form. So you can find selects with empty value:
$("select[value=]").first().focus()
Or iterate over all form elements, checking its value and type.
http://jsbin.com/UduNaGOh/1/edit?html,output
$(document).ready(function () {
$("#teste").click(function () {
var test = true;
$("#myform select").each(function(){
var select = $(this);
if(select.val() == 'none') {
select.addClass('fail');
select.focus();
test = false;
} else {
select.removeClass('fail');
}
});
if(test){
alert('well done');
$("#myform select").removeClass('fail');
// do your send stuff ...
}
});
});
I'm changing the class to style the empty selects.
So here is the css:
#myform > select.fail { background: red }
If you just need the number of empty selects you can use:
$('select:has(option[value="none"]:selected)').length

Categories