Dropdown won't display selected value after calling a function - javascript

So I'm very new to the world of jQuery and while writing a simple code a faced a problem that I couldn't figure out the solution for.
First of all, there's a function that updates the position of the form on the dropdown according to its index.
And then there's another function that will change the position of the form on the page when a new position is selected on the dropdown list:
$(document).ready(initialRank);
function initialRank() {
var itemIndex = $(".template-detail-field").length;
$('.field-rank').each(function () {
$(this).empty();
var pos = $(".field-rank").index($(this))+1;
for (var i = 1; i <= itemIndex; i++) {
if (i == pos) $(this).append('<option value="'+ i +'" selected>' + i + '</option>');
else $(this).append('<option value="' + i + '">' + i + '</option>');
}
});
}
$(document).on("change", ".field-rank", function () {
$(".template-detail-field").each(function () {
var sel = $(this).find(".field-rank").val();
var pre = $(".template-detail-field").eq(sel - 1);
$(this).insertBefore(pre);
});
initialRank();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="template-detail-field">
<p> Testing stuff 1 </p>
<select class="field-rank">
<option value="1" selected>1</option>
</select>
</div>
<div class="template-detail-field">
<p> Testing stuff 2 </p>
<select class="field-rank">
<option value="2" selected>2</option>
</select>
</div>
<div class="template-detail-field">
<p> Testing stuff 4 </p>
<select class="field-rank">
<option value="4" selected>4</option>
As you can see, after changing position I call the function initialRank() so that it updates the positions displayed for each form accordingly. The problem is after I do this, the dropdown list won't accept any input, and by that I mean when I choose a new position on the list the form doesn't change its position nor does the new chosen position is selected.
But when I rewrite the initialRank() code inside the change() function everything works fine:
$(document).ready(initialRank);
function initialRank() {
var itemIndex = $(".template-detail-field").length;
$('.field-rank').each(function () {
$(this).empty();
var pos = $(".field-rank").index($(this))+1;
for (var i = 1; i <= itemIndex; i++) {
if (i == pos) $(this).append('<option value="'+ i +'" selected>' + i + '</option>');
else $(this).append('<option value="' + i + '">' + i + '</option>');
} });
}
$(document).on("change", ".field-rank", function () {
$(".template-detail-field").each(function () {
var sel = $(this).find(".field-rank").val();
var pre = $(".template-detail-field").eq(sel - 1);
$(this).insertBefore(pre);
});
var itemIndex = $(".template-detail-field").length;
$('.field-rank').each(function () {
$(this).empty();
var pos = $(".field-rank").index($(this)) + 1;
for (var i = 1; i <= itemIndex; i++) {
if (i == pos) $(this).append('<option value="' + i + '" selected>' + i + '</option>');
else $(this).append('<option value="' + i + '">' + i + '</option>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="template-detail-field">
<p> Testing stuff 1 </p>
<select class="field-rank">
<option value="1" selected>1</option>
</select>
</div>
<div class="template-detail-field">
<p> Testing stuff 2 </p>
<select class="field-rank">
<option value="2" selected>2</option>
</select>
</div>
<div class="template-detail-field">
<p> Testing stuff 4 </p>
<select class="field-rank">
<option value="4" selected>4</option>
Can someone please explain to me what I was doing wrong.
Thank you.

Related

Show value of select option in html

I have a list with the tag, the item values ​​are obtained through an online spreadsheet. When selecting an option, the value does not appear in the html in real time. can anybody help me? I'm trying to solve it, but I can't find the error.
CODEPEN LINK EXAMPLE
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
console.log(data);
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
});
var totalWithTax = $('#divTax :selected').val();
$('.total').html(totalWithTax);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br>
Total:<div class="total"></div>
You to put the code that displays the selection in an event listener.
$(document).ready(function() {
var sheetURL =
"https://spreadsheets.google.com/feeds/list/1J0qyxUCCkvcFGZ6EIy9nDOgEuTlpI5ICVG3ZsBd_H-I/1/public/values?alt=json";
$.getJSON(sheetURL, function(data) {
var entryData = data.feed.entry;
jQuery.each(entryData, function() {
$("#divTax").append(
'<option hidden="hidden" selected="selected" value="0">CHOISE</option><option value="' + this.gsx$values.$t + '">' + this.gsx$names.$t + ' $' + this.gsx$values.$t + '</option>'
);
});
});
$("#divTax").change(function() {
var totalWithTax = $(this).val();
$('.total').text(totalWithTax);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select style="width: 80%;" id="divTax"></select>
<br> Total:
<div class="total"></div>

Getting the Target Value from a Form Stored as JS Variable

I'm trying to let the user select a value from a dropdown selector, which in turn will conditionally load a second dropdown selector. Once both fields have a value, a link will appear that has been dynamically generated from those two values.
For example: User selects "audi" from first form, which shows the audi form, then they select "r8" from the second form, which would produce www.example.com/**audi**/**r8**/
However, it seems that I can't get the event.target.value of the second dropdown; I'm assuming because when the script loads the value isn't there.
How would I go about writing this so I could get both values, then fill it into a link?
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
</form>
<br><br>
<div class="model-field" id="model-field"></div>
<div class="button-field">
<h4>link:</h4>
<p id="button-field"></p>
</div>
<script>
var audiForm = '<form class="audi-model">' +
'<select name="audi-model" id="audi-model">' +
'<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>' +
'</select>' +
'</form>';
var vwForm = '<form class="vw-model">' +
'<select name="vw-model" id="vw-model">' +
'<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>' +
'</select>' +
'</form>';
var carsForm = document.getElementById("cars");
if (carsForm) carsForm.addEventListener('change', function(event) {
var carType = (event.target.value);
console.log(carType);
if(event.target.value == 'audi') {
document.getElementById("model-field").innerHTML = audiForm;
}
if(event.target.value == 'volkswagen') {
document.getElementById("model-field").innerHTML = vwForm;
}
});
var audiModelForm = document.getElementById("audi-model");
if (audiModelForm) audiModelForm.addEventListener('change', function(event) {
var audiModel = event.target.value;
console.log(audiModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + audiModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
var vwModelForm = document.getElementById("vw-model");
if (vwModelForm) vwModelForm.addEventListener('change', function(event) {
var vwModel = event.target.value;
console.log(vwModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + vwModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
</script>
Another solution is to store the options in a javascript object, and just auto fill in the select as needed. This will allow you to easily update the system to accept more makes and models.
var data = {
"audi": ["a4","a5","r8"],
"volkswagen": ["Bug","Jetta","Golf"]
};
var make = document.querySelector("#cars");
var model = document.querySelector("#model");
var link = document.querySelector("#link");
make.addEventListener("change",function(){
if(make.value != ""){
var models = data[make.value];
var length = model.options.length;
for (i = length-1; i >= 0; i--) {model.options[i] = null;}
link.innerHTML = "";
let opt= document.createElement("option");
opt.text = "Select " + make.value + " Model";
opt.value = "";
model.appendChild(opt);
models.forEach(function(k,v){
let opt= document.createElement("option");
opt.text = k;
opt.value = k;
model.appendChild(opt);
});
}
});
model.addEventListener("change",function(){
if(model.value != ""){
link.innerHTML = '<h4>' + make.value + '/' + model.value + '</h4>';
}
});
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
<select name="model" id="model"></select>
</form>
<div id="link">
</div>
The problem is that your code attempts to find and set up an event handler for the second dropdown before it gets created. Moving that code so that it is within the first event handler makes it work.
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
</form>
<br><br>
<div class="model-field" id="model-field"></div>
<div class="button-field">
<h1>link:</h1>
<p id="button-field"></p>
</div>
<script>
var audiForm = '<select name="audi-model" id="audi-model">' +
'<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>' +
'</select>' +
'</form>';
var vwForm = '<select name="vw-model" id="vw-model">' +
'<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>' +
'</select>' +
'</form>';
var carsForm = document.getElementById("cars");
if (carsForm) carsForm.addEventListener('change', function(event) {
var carType = (event.target.value);
console.log(carType);
if(event.target.value == 'audi') {
document.getElementById("model-field").innerHTML = audiForm;
}
if(event.target.value == 'volkswagen') {
document.getElementById("model-field").innerHTML = vwForm;
}
var audiModelForm = document.getElementById("audi-model");
if (audiModelForm) {
audiModelForm.addEventListener('change', function(event) {
var audiModel = event.target.value;
console.log(audiModel);
var link = '<h4>' + carType + '/' + audiModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
}
});
var vwModelForm = document.getElementById("vw-model");
if (vwModelForm) vwModelForm.addEventListener('change', function(event) {
var vwModel = event.target.value;
console.log(vwModel); // Doesn't work as the above line is likely null
var link = '<h4>' + carType + '/' + vwModel + '</h4>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
</script>
But really, a better solution is to have the select already statically built from the start, but just hidden. Then, you can set up its handler right away, but only populate its option elements after the first selection has been made. You'll also only need one secondary select for whatever set of option elements are relevant based on the first choice.
Also, you shouldn't be creating form elements that wrap each select. If you are going to submit this data somewhere, you just want one form around all the form elements. And, if not, you don't need a form at all.
Lastly, don't use HTML heading elements because of the size that they make your text. You can't have an h4 unless you've already got an h3. Use CSS to style your text.
var audi = '<option value="" disabled selected>Select Audi model</option>' +
'<option value="a4">A4</option>' +
'<option value="a5">A5</option>' +
'<option value="r8">r8</option>';
var vw = '<option value="" disabled selected>Select VW model</option>' +
'<option value="jetta">Jetta</option>' +
'<option value="passat">Passat</option>';
var cars = document.getElementById("cars");
var models = document.getElementById("models");
cars.addEventListener('change', function(event) {
if(event.target.value == 'audi') {
models.innerHTML = audi;
} else if(event.target.value == 'volkswagen') {
models.innerHTML = vw;
}
models.classList.remove("hidden"); // Time to show the second list
});
models.addEventListener('change', function(event) {
var link = '<h1>' + cars.value + '/' + models.value + '</h1>';
console.log(link);
document.getElementById("button-field").innerHTML = link;
});
.hidden { display:none; }
h1 { font-size:.8em;}
<form>
<select name="cars" id="cars">
<option value="" disabled selected>Select your Car</option>
<option value="audi">Audi</option>
<option value="volkswagen">Volkswagen</option>
</select>
<div class="model-field" id="model-field">
<select name="models" id="models" class="hidden"></select>
</div>
</form>
<div class="button-field">
<h1>link:</h1>
<p id="button-field"></p>
</div>

matching text of option tag using filter function

I have two select box. on change event of first select box, i'm adding that text into second select box. but i don't want to add duplicate record.for this i'm using filter function,(if any text that has already added then i don't want to add again) but it's not working as i want.
html
<select id="ddlCategory">
<option value="0">Select Category</option>
<option value="1">Category 1</option>
<option value="2">Category 2</option>
<option value="3">Category 3</option>
</select>
<select multiple="multiple" id="my-select" name="my-select[]" class="multiDrop"> </select>
<select multiple="multiple" id="your-select" name="my-selectyour[]" class="multiDrop">
myJs:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($('#your-select > option').hasClass(getCategory)) {
$("#your-select > option").filter(function (index) {
if ($(this).html() == getText) {
return;
}
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
});
} else {
$('#your-select').html('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});
Jsfiddle
Here you go... my edited fiddle: http://jsfiddle.net/stoz1m6v/2/
This way it does not duplicate the entries in myselect...
you had some checking of class/category there which I removed, because I found it incorrectly done, however I could not comprehend how exactly you wanted to check the category...
and the script goes like this... I have changed only the change handler of the my-select:
$('#my-select').change(function () {
var getValue = $(this).find('option:selected').val();
var getText = $(this).find('option:selected').text();
var getCategory = $('#ddlCategory').find('option:selected').text();
if ($("#your-select > option").filter(function (index) {
return $(this).html() == getText; }).length ==0) {
$('#your-select').append('<option value="' + getValue + '" class="' + getCategory + '">' + getText + '</option>');
}
});

How to insert values in textbox to select option

HTML
<input type="text" value="" id="ip1" class="ip1" />
<input type="button" value="Add" class="bt1" id="bt1">
</br>
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
JQUERY
$(document).ready(function(e) {
$(".bt1").click(function(){
var opt = $("#ip1").val();
});
});
Hi friends here i want to add value from text box to select option using jquery,
i got the value from textbox but don't know how to insert, help me.
you can do like this:
HTML:
<select id="List">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
</select>
JQUERY:
$(".bt1").click(function(){
var opt = $("#ip1").val();
$('#List')
.append($("<option></option>")
.attr("value",opt )
.text(opt));
});
FIDDLE DEMO
Use append
$(document).ready(function(e) {
$(".bt1").click(function(){
var opt = $("#ip1").val();
$("select").append('<option value="' + opt+ '">' + opt +'</option>')
});
});
$(document).ready(function (e) {
$(".bt1").click(function () {
var opt = $("#ip1").val();
$('select').append(' <option value="' + opt + '">' + opt + '</option>')
});
});
DEMO
$(".bt1").on('click',function () {
var optionval= $("#ip1").val();
$('select').append(' <option value="' + opt + '">' + opt + '</option>')
});
$(document).ready(function(e) {
$("select").change(function(){
var opt = $("#ip1").val();
});
});
Try this:
$(".bt1").click(function () {
var opt = $("#ip1").val();
//check if option already exists in the drop down
if (!$("select").find("option[value='" + opt + "']").length) {
//add option to the drop down
$("select").append("<option value='" + opt + "'>" + opt + "</option>");
}
//select entered option
$("select").find("option[value='" + opt + "']").attr("selected", "selected");
});
See DEMO here.
Hope this will help
$(document).ready(function (e) {
var $txtVal = $('#ip1');
$(".bt1").click(function () {
var opt = $("#ip1").val();
if($txtVal.val()){
$('<option />', { text: $txtVal.val(),value: $txtVal.val()}).appendTo('select');
}
});
});
FIDDLE HERE >>

text field within two drop down

This script produce a drop down form where I can select the number of drop down fields that can be displayed. However I'm kind of stuck on that. My problem now is how to make default text field base on the value of the second drop down form? For example if I select 'Ms.' It will produce Two text field else it will just one text field.
jQuery
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val();
var i = 0;
var html = '';
for (i = 1; i <= num; i++) {
html += '<br>' + i + '. <select name="gender4-' + i + '">' + '</' + 'option>' + '<option value=' + '"m">Mr. ' + '</option' + '>' + '<option value=' + '"f">' + 'Ms. ' + '</option' + '>' + '</select' + '></br>';
}
$('#list').html(html);
});
});​
HTML
<select id="bookinfo_adult" name="bookinfo_adult">
<option value="0">- SELECT -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
<div id="list"></div>
Not quite sure what you're asking, but I guess you want to display input fields dynamically based on the current selection in your generated select elements?
So how about this?
HTML:
<input type="text" id="bookinfo_adult">
<div id="list"></div>
CSS:
#list input { display: none; }
JS:
$(document).ready(function() {
$('#bookinfo_adult').change(function() {
var num = $('#bookinfo_adult').val(), i = 0, html = '';
for (i = 1; i <= num; i++) {
html += '<div>' + i + '. \
<select name="gender4-'+i+'"><option/><option value="m">Mr.</option><option value="f">Ms.</option><select> \
<input type="text" class="ms"> <input type="text" class="mr">\
</div>';
}
$('#list').html(html);
});
$(document).on("change", "#list select", function(){
var parent = $(this).closest("div");
switch ($(this).val()) {
case "m": parent.find(".mr").show(); parent.find(".ms").hide(); break;
case "f": parent.find("input").show(); break;
default: parent.find("input").hide(); break;
}
});
});
I just added two text fields (hidden with CSS at first) and wrapped every "line" of your dropdown in a div for easier selection. Then a onchange handler is created that works for all elements being added to the DOM in the future (once you could use jQuery.live() for that, but it's deprecated as of version 1.7). The handler itself should be self-explanatory. ;)
Working example: http://jsfiddle.net/DfXEE/

Categories