Changing values in dynamically generated html using Jquery - javascript

As the title says, I'm wondering if there's a way to change the value of html items that are generated by jquery. Here's the code that I currently have:
the javascript
<script type="text/javascript">
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
$(".row:first").clone(true).insertAfter(".row:last");
$('#dateDueMonth['+i+']').val(curentMonth + 1);
})
});
</script>
My thought here was that after the row was cloned, I could then change the dropdowns content based upon it's current name, but obviously that's not working, and I've been unable to find a way to "hook" into dynamic html content.
and the base html
<select id="months" name="months">
<option selected 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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
</td><div id="showRows"><div class="row" id="row[]"><td class="td_alt"><select id="dateDueMonth[]" name="dateDueMonth[]" >
<option value="0">Select</option>
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">Mar</option>
<option value="4">Apr</option>
<option value="5">May</option>
<option value="6">Jun</option>
<option value="7">Jul</option>
<option selected value="8">Aug</option>
<option value="9">Sep</option>
<option value="10">Oct</option>
<option value="11">Nov</option>
<option value="12">Dec</option>
</select>
<select id="dateDueYear[]" name="dateDueYear[]">
<option value="2005">2005</option>
<option value="2006">2006</option>
<option value="2007">2007</option>
<option value="2008">2008</option>
<option value="2009">2009</option>
<option value="2010">2010</option>
<option selected value="2011">2011</option>
</select>
Now the generation of dynamic html and form submission works great. Gives me the data that I can use for my back end code. However having it so that I can increment the values in the various dropdowns as I see fit would make data entry by the folks using this page a whole lot easier, hence the issue.
To all that reply, thanks for your help with this jquery/JS noob.
EDIT: For this what I want to have is a form that can spawm multiples copies of the first line encased within the showRows div. When this is submitted, I want it to be able to collect that information in arrays for each select/input statement for the rows that are generated. For example if I selected two months, dateDueMonth, dateDueYear, and amount would be arrays in my form that would have two entries each. The current code does this, but by default it has the default elements for the dropdown menus set the same as the row of HTML that it is cloning.

Not sure what you want to do, but it should work like this
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
var arr;
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++)
arr=[$(".row:first").clone(true).insertAfter(".row:last")];
$('#dateDueMonth['+i+']').val(curentMonth + 1); //don't know why its here
arr[0].text("your value"); //apply the index you wanna change
})
});

Are you trying to achieve this kind of markup? Demo
<div id="showRows"><div class="row" id="row[0]"><select id="dateDueMonth[0]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[0]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
</div><div class="row" id="row[1]"><select id="dateDueMonth[1]" name="dateDueMonth[0]">
<option value="0">Select</option>
...
</select>
<select id="dateDueYear[1]" name="dateDueYear[0]">
<option value="2005">2005</option>
...
</select>
...
This may be what you need. See my demo linked above.
for (var i = 1; i <= this.selectedIndex; i++) {
row = $(".row:first").clone(true)[0];
row.id = "row["+i+"]";
$(row).find("[id^='dateDueMonth']").attr("id","dateDueMonth["+i+"]").val((curentMonth + i) % 12 + 1);
$(row).find("[id^='dateDueYear']").attr("id","dateDueYear["+i+"]");
$(row).insertAfter(".row:last");
}

you cannot use ids as array in JavaScript. if you want, you have to put array index as well when you create element. or else just access the select element as bellow
$(document).ready(function() {
$('#months').change(function() {
var currentDate = new Date();
var curentMonth = currentDate.getMonth();
var curentYear = currentDate.getYear();
$(".row:not(:first)").remove();
for (var i = 0; i < this.selectedIndex; i++) {
$(".row:first").clone(true).insertAfter(".row:last");
$('.row:last select').val(curentMonth + 1);
}
})
});
Working sample

Related

Swap a select text with javascript?

I have a example code here:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
I want to swap se1 and se2 . Here is my code i tried:
function swap() {
var sel1 = $("#se1 option:selected").text();
var sel2 = $("#se2 option:selected").text();;
console.log(sel1, sel2)
$("#se1").val(sel2);
$("#se2").val(sel1);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>
It's work but it require Jquery 1.2.3 but i want to use Jquery 2.1.3. If i change script url to "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js" but it isn't work
Thanks for help!
You shouldn't be swapping the values or the text of the two selected items in the lists. You just need to swap which item is selected in each list. Once that is done, that option will have whatever value the list has set up for it.
The version of JQuery you use here doesn't matter since what you are doing requires JQuery operations that have been in JQuery since the beginning.
var sel1 = $("#se1");
var sel2 = $("#se2");
function swap() {
let selection1 = sel1[0].selectedIndex; // Store the first list's selection
sel1[0].selectedIndex = sel2[0].selectedIndex;
sel2[0].selectedIndex = selection1;
// Test
console.log(sel1.val(), sel2.val());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<select id="se1">
<option value="1">DOG</option>
<option value="2">CAT</option>
<option value="3">BIRD</option>
</select>
<button onclick="swap()">SWAP</button>
<select id="se2">
<option value="4">DOG</option>
<option value="5">CAT</option>
<option value="6">BIRD</option>
</select>

I want to keep first 2 options and delete remaining in a select element with jquery,

I want to delete all options in a select element with jquery, except for the first n.
where n is amount of options to keep.
As per your conversation you want that except first 2 option others will be removed. Please try below code it will help you::
Assuming sub_buyer is your selectbox's ID
$( document ).ready(function() {
$('#sub_buyer').find('option').not(':nth-child(1), :nth-child(2)').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control" name="sub_buyer" id="sub_buyer">
<option value="1">FB</option>
<option value="2">RM</option>
<option value="3">Joey</option>
<option value="4">Isaac</option>
<option value="5">Christina</option>
<option value="6">James</option>
<option value="7">Armando</option>
<option value="8">Kent</option>
<option value="9">Tyler</option>
<option value="10">Michael</option>
<option value="11">Dylan</option>
<option value="12">Ryan</option>
<option value="13">John-Ralph</option>
<option value="14">John-Mike</option>
</select>
Working jsfiddle url: https://jsfiddle.net/xya0p3ym/
I can't remember a way to find the last 2 elements of a collection as a selector but this will do it:
$('#mySelect')
.find('option:last-child')
.remove();
$('#mySelect')
.find('option:last-child')
.remove();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="mySelect">
<option value="">Select one</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>
</select>
function removeLast (a){
var arr = $("#select_id option");
for(var i = 0; i<a;i++){$(arr[arr.length-1]).remove();}
};
removeLast(number_of last_items_to_delete);
This code selects only option tag, not all children and can remove as many last childs as you want.
This is working:
$(document).ready(function(){
var n = 4;
var options = $('select').children();
for (var i = 0; i < options.length; i++) {
if (i >= n) {
options[i].remove();
}
}
});

How to get the values and text of all the options of select element

I have a select element with a huge list of options (more than 2000).
I'd like to get the values and name of each option, one by line.
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
What I'd like is,
51421 = City one
51422 = City two
51423 = City three
51424 = City four
One option per line..
Thanks.
First, you need to iterate through the options array, and collect the values & text into a data array, then you can do whatever you feel like with it, for instance print it to the page like so:
var data = [];
$('#county_city option').each(function(){
var current = $(this);
data.push({
value: current.val(),
text: current.html()
})
});
$.each(data, function(){
console.log(this);
$('#result').append(this.value + ': ' + this.text)
.append('<br />');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
<div id="result"></div>
use the following code :-
HTML
<select name='county_city' id='county_city'>
<OPTION value="51421">City one</OPTION>
<OPTION value="51422">City two</OPTION>
<OPTION value="51423">City three</OPTION>
<OPTION value="51424">City four</OPTION>
</select>
JQuery
$(document).ready(function() {
$("#county_city OPTION").each(function(index){
alert(this.value);
alert(this.text);
});
});

Not able to get value from the dynamically generated drop down

Problem
I've 2 diff drop down select box. First select box is static whereas the other is dynamically generated according to the value selected in first select box. The values are getting generated properly but when I try to display the value of second select box it only display the first option's value, even if selected 3rd or 4th option. Please see code and example below:
Javascript Code
function wpPopulate(){
$('#win_parameter').empty();
var classes = document.getElementById('noOfClasses').value;//total number of classes
var percent = (100/classes);//to get a percentage for single class
//console.log("1 class: "+percent+"%");
//Define Variables
var wpOptions = '';
var dd = '';
for(var i=1; i<=classes; i++){
dd = parseFloat(percent*i).toFixed(2)+"% ("+i+" class)";
wpOptions += '"'+parseFloat(percent*i).toFixed(2)+'": "'+dd+'", ';
}
wpOptions = "{"+wpOptions.substr(0, (wpOptions.length-2))+"}";
wpOptions = $.parseJSON(wpOptions);
var selectValues = wpOptions;
$.each(selectValues, function(key, value) {
$('#win_parameter')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
}
HTML Code:
(Select box 1)
<select name="noOfClasses" id="noOfClasses" onChange="wpPopulate();">
<option value="1" selected="selected">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>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
</select>
(Select box 2)
<select name="win_parameter" id="win_parameter">
</select>
Example:
When selected 5 classes in first select box the options come in second select box are as follows. When I select anything apart from 20% it still displays as 20%, example 60%. Any help or guidance will be much appreciated!!
<select name="win_parameter" id="win_parameter">
<option value="20.00">20.00% (1 class)</option>
<option value="40.00">40.00% (2 class)</option>
<option value="60.00">60.00% (3 class)</option>
<option value="80.00">80.00% (4 class)</option>
<option value="100.00">100.00% (5 class)</option>
</select>

Adjusting a webpage's font with javascript

I'm a beginner with javascript, and I'm (with permission) building a website to host the stories of an amateur author I like. I'm trying to add a pair of drop down boxes at the top of the screen that can adjust text size and font family for the chapter. The drop downs are there and I've placed a div container around the chapter text, but the font isn't changing. Here's the applicable code:
Font: <select name='fontface' onchange="var ftxt = getItem('fluidtext'); if(ftxt)ftxt.style.fontFamily = this.options[this.selectedIndex].value;">
<option value='Helvetica' selected='selected'>Helvetica</option>
<option value='Verdana'>Verdana</option>
<option value='Times New Roman'>Times New Roman</option>
<option value='Courier New'>Courier New</option>
<option value='Georgia'>Georgia</option>
</select>
<select name='fontsize' onchange="var ftxt = getItem('fluidtext'); if(ftxt)ftxt.style.fontSize = this.options[this.selectedIndex].value;">
<option value='8pt'>8pt</option>
<option value='10pt'>10pt</option>
<option value='12pt' selected='selected'>12pt</option>
<option value='14pt'>14pt</option>
<option value='16pt'>16pt</option>
<option value='18pt'>18pt</option>
<option value='24pt'>24pt</option>
<option value='32pt'>32pt</option>
<option value='40pt'>40pt</option>
<option value='48pt'>48pt</option>
<option value='60pt'>60pt</option>
<option value='75pt'>75pt</option>
<option value='90pt'>90pt</option>
</select>
I've added " div id='fluidtext' " further down the page where the chapter starts, and " /div " at the end of the chapter. There's no inline code in the story chapters except occasional bold and italic tags. The page is formatted using an external CSS style sheet.
The complete page (minus the CSS formatting) can be found here:
https://dl.dropboxusercontent.com/u/59191190/tower02.html
Any help would be appreciated!
I am going to write you the cleanest answer:
CodePen solution
The reason why I have added 'onkeyup' is due to FireFox not firing 'onchange' when cycling through with keyboard navigation.
Also, I have used an auto executing lambda function to ensure that we do not pollute the window object with our fluff variables.
Edit: For anyone who does not want the CodePen solution
HTML
Font:
<select id="fontface" name='fontface'>
<option value='Helvetica'>Helvetica</option>
<option value='Verdana'>Verdana</option>
<option value='Times New Roman'>Times New Roman</option>
<option value='Courier New'>Courier New</option>
<option value='Georgia'>Georgia</option>
</select>
<select id="fontsize" name='fontsize'>
<option value='8pt'>8pt</option>
<option value='10pt'>10pt</option>
<option value='12pt' selected='selected'>12pt</option>
<option value='14pt'>14pt</option>
<option value='16pt'>16pt</option>
<option value='18pt'>18pt</option>
<option value='24pt'>24pt</option>
<option value='32pt'>32pt</option>
<option value='40pt'>40pt</option>
<option value='48pt'>48pt</option>
<option value='60pt'>60pt</option>
<option value='75pt'>75pt</option>
<option value='90pt'>90pt</option>
</select>
<p id="fluidtext">
This is my fluid text
</p>
JS
(function() {
//Assuming document is ready
function onFontFaceChange() {
if(fluidTextNode) fluidTextNode.style.fontFamily = this.options[this.selectedIndex].value;
}
function onFontSizeChange() {
if(fluidTextNode) fluidTextNode.style.fontSize = this.options[this.selectedIndex].value;
}
var fontFaceNode = document.getElementById('fontface'),
fontSizeNode = document.getElementById('fontsize'),
fluidTextNode = document.getElementById('fluidtext');
if(fontFaceNode) fontFaceNode.onkeyup = fontFaceNode.onchange = onFontFaceChange;
if(fontSizeNode) fontSizeNode.onkeyup = fontSizeNode.onchange = onFontSizeChange;
}());
You're trying to call getItem function which is not defined.
You need to declare it:
<script>
var getItem = function(item) {
return document.getElementById(item);
};
</script>
Also try to avoid handling events in DOM attributes. I'd suggest the complete code look like this:
<script>
var getItem = function(item) {
return document.getElementById(item);
};
getItem('fontface').addEventListener('change', function() {
var ftxt = getItem('fluidtext');
if(ftxt)
ftxt.style.fontFamily = this.options[this.selectedIndex].value;
});
getItem('fontsize').addEventListener('change', function() {
var ftxt = getItem('fluidtext');
if(ftxt)
ftxt.style.fontSize = this.options[this.selectedIndex].value;
});
</script>
Font:
<select id="fontface" name='fontface'>
<option value='Helvetica' selected='selected'>Helvetica</option>
<option value='Verdana'>Verdana</option>
<option value='Times New Roman'>Times New Roman</option>
<option value='Courier New'>Courier New</option>
<option value='Georgia'>Georgia</option>
</select>
<select id="fontsize" name='fontsize'>
<option value='8pt'>8pt</option>
<option value='10pt'>10pt</option>
<option value='12pt' selected='selected'>12pt</option>
<option value='14pt'>14pt</option>
<option value='16pt'>16pt</option>
<option value='18pt'>18pt</option>
<option value='24pt'>24pt</option>
<option value='32pt'>32pt</option>
<option value='40pt'>40pt</option>
<option value='48pt'>48pt</option>
<option value='60pt'>60pt</option>
<option value='75pt'>75pt</option>
<option value='90pt'>90pt</option>
</select>
One thing worth mentioning is that addEventListener isn't cross browser. I'd suggest using jQuery and on method instead of addEventListener. Then the whole JS could look like this:
<script>
(function( $ ) {
$(document).ready(function() {
$('#fontface').on('change', function() {
var ftxt = $('#fluidtext');
if(ftxt)
ftxt.style.fontFamily = this.options[this.selectedIndex].value;
});
$('#fontsize').on('change', function() {
var ftxt = $('#fluidtext');
if(ftxt)
ftxt.style.fontSize = this.options[this.selectedIndex].value;
});
});
})(jQuery);
</script>
Add this to your page in order to define the missing getItem function:
<script>
function getItem(a) { return document.getElementById(a); }
</script>

Categories

Resources