JQuery Append Text Dynamically by Onblur input value - javascript

When i give input (1) then its successfully append text. But when i erase then input value and again give input(2) then its increasing with previous value(1+2=3). Where loop count previous and present value
$(document).ready(function(){
var i=0;
$("#flatcount").blur(function() {
var floor = (this).value;
for(i=1;i<=floor;i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});

You need to empty the element.before append like $('#row').empty()
$(document).ready(function() {
var i = 0;
$("#flatcount").blur(function() {
var floor = $(this).val();
$('#row').empty() //empty
for (i = 1; i <= floor; i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="flatcount">
<p id="row"></p>

use this code i think it will work
$(document).ready(function(){
var i=0;
$("#flatcount").blur(function() {
$("#row").empty();
var floor = (this).value;
for(i=1;i<=floor;i++) {
$('#row').append('<p>This is appended text</p><br>');
}
});
});

Related

For Loop Dependent on Number Input

I'm trying to repeat a div, the number of times dependent on the number chosen in a number input field, but currently when the number input is changed the values are being multiplied. So if you go from 2 to 3 it repeats the div 6 times instead of just 3. How can I reset the loop so it's using only the current number?
http://jsfiddle.net/deliciouslycheesy/6rb94mry/
$('#numRepeat').on('change keyup input', function () {
var el = $(".repeat-me").get(0);
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();
You need to remove the ones that were added before:
$('#numRepeat').bind('change keyup input', function () {
var el = $(".repeat-me").get(0);
$(".repeat-me:not(:first)").remove();
var numRepeat = $("#numRepeat").val();
for(var i = 1;i < numRepeat;i++){
var newEl = $(el).after(el.cloneNode(true));
}
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="2"/>
<div class="repeat-me">REPEAT</div>
JSFiddle
I'm not sure why you're using three event change keyup input, just input event will detect changes inside input field, check the Updated fiddle.
I suggest to separate the model of repeated div from the result, i think that will make code more clear, and because you're using JQuery you can replace cloneNode() by clone().
Hope this helps.
$('#numRepeat').on('input', function () {
var el = $("#model-div .repeat-me");
var numRepeat = $(this).val();
$('#result-div').empty(); //Clear the result div
for(var i = 0 ; i < numRepeat ; i++)
{
$('#result-div').append( $(el).clone(true) );
}
})
#model-div{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="numRepeat" value="0"/>
<div id="model-div">
<div class="repeat-me">REPEAT</div>
</div>
<div id="result-div"></div>

How to append select-options from multi-dimension array?

jsfiddle
HTML:
<select class="s1"></select>
<select class="s2"></select>
JS:
var test = [
["a","bsafd","cfsaf"],
["b","cvxb","cfsf"],
["c","hjymb","cfsaf"],
["d","vhthb","fsfc","fasfsa"],
["e","fsdb","fsfac"],
["f","zxczb","vcxc","fsafsd"],
["g","yjhdb","bvcbc"],
["h","vbnvb","yutkfc"],
["i","nbcvnb","ndnfgnmc"],
["j","ikgnb","ncnc"],
["k","fgncb","kjuc"]
];
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
for(var i=0;i<test.length;i++){
if(test[i].indexOf(value)){
for(var j=0;j<test[i].length;i++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
I can get the first value from array test and append to the first select area. But I stacked on the second step. I want to append values to the second select area according to the user selection.
Fon instance, user select "a". The next two values should be append to the second area from the sub array which lead with "a".
Could someone tell me what am I done wrong and how to finish it?
Try the below code [check the inline comments where you did mistake],
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option value='"+test[i][0]+"'>"+test[i][0]+"</option>");
// -----------------^ add value to all options
}
$(".s1").on("change", function(){
var value = $(this).val();
$(".s2").html('');// first make the second drop down blank
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
for(var j=0,l=test[i].length;j<l;j++){
//----------------^ j++ not i++
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
});
});
Live Demo
Alternatively, if you make your json as key-value pair to differentiate the data for different drop down then it would more simpler to use it like,
// json where keys are used fro first drop down and its values are used for second one
var test = {
"a":["bsafd","cfsaf"],
"b":["cvxb","cfsf"],
"c":["hjymb","cfsaf"],
"d":["vhthb","fsfc","fasfsa"],
"e":["fsdb","fsfac"],
"f":["zxczb","vcxc","fsafsd"],
"g":["yjhdb","bvcbc"],
"h":["vbnvb","yutkfc"],
"i":["nbcvnb","ndnfgnmc"],
"j":["ikgnb","ncnc"],
"k":["fgncb","kjuc"]
};
$(function(){
$.each(test,function(i,v){
// store all keys to first drop down
$(".s1").append("<option value='"+i+"'>"+i+"</option>");
});
$(".s1").on("change", function(){
var value = this.value;
$('.s2').html('');
if(value){
// get the value for the key which is selected
$(test[value]).each(function(key,data){
$(".s2").append("<option value='"+data+"'>"+data+"</option>");
});
}
});
});
Working Demo
$(".s1").on("change", function(){
var value = $(this).val();
var option = '';
for(var i=0;i<test.length;i++){
/* Checking for first index */
if(test[i][0] == value){
for(var j = 1;j<test[i].length;j++){
/* creating options */
option += '<option>'+test[i][j]+'</option>';
}
}
}
/* remove previous options and prepend new option by selection */
$(".s2").empty().prepend(option);
});
Please try this..
check this fiddle
for(var i=0;i<test.length;i++){
if(test[i][0]==value){
(var j=1;j<test[i].length;j++){
$(".s2").append("<option>"+test[i][j]+"</option>");
}
}
}
It is not a multi-dimension array, so you need to loop through or filter() the original array to find the matching row and then add the elements of that array starting from 1 instead of 0 to ignore the "key" value:
$(function(){
for(var i=0;i<test.length;i++){
$(".s1").append("<option>"+test[i][0]+"</option>");
}
$(".s1").on("change", function(){
var value = $(this).val();
// find the first array which starts with value
var arr = test.filter(function(v){
return v[0] == value;
})[0];
// store a reference to .s2 so you don;t need to find it every time
var s2 = $(".s2");
// remove previous options
s2.empty();
for(var i = 1; i < arr.length; i++){
s2.append("<option>"+arr[i]+"</option>");
}
});
});
Updated Fiddle

JQuery: for condition is not able to complete due to .replaceWith manipulation

I am trying to get a line of JQuery script to read every paragraph string found in a div and split that paragraph every time there is a ','. My issues is that I am unable to POST all of the array at once, so the replaceWith function only outputs the first value of the array because the rest of the array is deleted when the for condition returns to increment to myArray[1].
Is there anyway for me to post every value in the 'array of splits' to separate html elements without leaving the initial string and/or turning every created element a child of the previous element?
DEMO
http://jsfiddle.net/ry25Q/
HTML
<div class="data">
<i>days_of_week</i>
<p>mon,tue,wed,thur,fri,sat,sun</p>
</div>
<div>
<input type="button" class="btnClick Button" value="Click" />
</div>
JS CODE
$(function () {
$('.btnClick').click(function () {
var data = $('.data p').text();
var splitter = data.split(',');
for (var i = 0; i < splitter.length; i++) {
$(".data p").replaceWith("<span class='dataseg'>" + splitter[i] + "</span>")
}
});
});
You don't need a loop. Since you're only replacing one p element, just call .replaceWith() once with the full HTML string you're inserting.
DEMO: http://jsfiddle.net/Vfk4e/
$(function () {
$('.btnClick').click(function () {
var p = $('.data p');
var splitter = p.text().split(',');
var open = "<span class='dataseg'>";
var close = "</span>"
p.replaceWith(open + splitter.join(close + open) + close)
});
});
Can't you just add $('.data p').text(''); before your for statement? This will clear the contents,t hen your .append from your fiddle will work just fine.
$(function () {
$('.btnClick').click(function () {
var data = $('.data p').text();
var splitter = data.split(',');
$('.data p').text('');
for (var i = 0; i < splitter.length; i++) {
$(".data p").append("<span class='dataseg'>" + splitter[i] + "</span>")
}
});
});
Try to create a variable for the span element you wish to replace the <p> element with. Then inside of your for loop, sequentially add your data to the span element. After the loop, close your span and then call replaceWith() with the span variable.
$(function () {
$('.btnClick').click(function () {
var data = $('.data p').text();
var splitter = data.split(',');
var daySpan = "<span class='dataseg'>";
for (var i = 0; i < splitter.length; i++) {
daySpan += splitter[i];
}
daySpan += "</span>";
$(".data p").replaceWith( daySpan );
});
});
Demo: http://codepen.io/imajedi4ever/pen/kpzCD/?editors=101

How can I get td first child value?

I have a table where I want, for each row, get the first td and for this td I want the first input child value.
I'm able to get the markup for the input, but I can't extract the value.
Here is my code:
$('#table-unidades tr:not(:last-child)').each(function () {
$('td:first-child', this).each(function () {
var firstCell = $(this).children().eq(0);
var text = firstCell.html();
alert(text);
})
});
my alert outputs this:
<input type="text" name="unidades-first-td" value="UN - Unidade" disabled />
But all I want is the value.. I've tried with .text(), .val() , but it didn't work...
try this and get them all as an array once:
$("#table-unidades tr:not(:last-child)>td:first-child input:text:first-child")
.map(function () {return $(this).val(); }).get();
You need to use val() to get value of input, then use find() to find input field inside td
$('#table-unidades tr:not(:last-child)').each(function() {
$('td:first-child', this).each(function() {
var firstCell = $(this).children().eq(0);
var text = firstCell.find('input').val();
alert(text);
})
});
You don't need to use two each loops to find first child, also you must use .val() to get the value of an input, try this
$('#table-unidades tr:not(:last-child)').each(function () {
var text = $(this).find('td:first input:first').val();
});
Try
var val = firstCell.find('input').val();
alert(val);
Use .val() to get the value of the input element
$('#table-unidades tr:not(:last-child) td:first-child').each(function () {
var firstCell = $(this).children('input');
var text = firstCell.val();
alert(text);
});
var trs = $("tr", ".my-table");
for(var i=0; i<trs.length; i++){
var nval = $("td:first-child > input", trs[i]).val();
console.log(nval);
}
1 don't care about the reputation.
2 if it doesn't work, make it work.

Complex Javascript and HTML question, <select> and <textarea>

Let's say I have multiple select box with options that have different options. On click, I want to values to be transported to a textarea. I'll try to show them in images.
Possible without jQuery as well and not really complex.
Have this JS:
<script type="text/javascript">
function CopyValues(oDDL, sTargetId) {
var arrValues = new Array();
for (var i = 0; i < oDDL.options.length; i++) {
var curOption = oDDL.options[i];
if (curOption.selected)
arrValues.push(curOption.value);
}
document.getElementById(sTargetId).value = arrValues.join("\n");
}
</script>
Activate it from within the select tag like this:
<select multiple="multiple" onclick="CopyValues(this, 'txtData');">
And whenever user click the drop down the selected values will be copied to textarea with the given ID, e.g.:
<textarea id="txtData"></textarea>
Live test case: http://jsfiddle.net/yahavbr/UBwML/
Assuming your textarea has an ID of "text":
(Note: this uses the jQuery framework, which makes things a lot easier. See section further down for non-jQuery solution):
$('select').change(function () {
$('#text').val($(this).find('option:selected').text());
});
This will replace any text already inside the textarea though. If you want to simply add it to the end (with a space), then:
$('select').change(function () {
$('#text').val($('#text').val() + ' ' + $(this).find('option:selected').text());
});
Pure Javascript solution:
var selects = document.getElementsByTagName('select'),
textarea = document.getElementById('text');
for (var i = 0, select; select = selects[i]; i++) {
select.selectedIndex = -1;
select.onchange = (function (s) {
return function () {
textarea.value +=
' ' + s.options[s.selectedIndex].innerHTML;
s.selectedIndex = -1;
};
})(select);
}
Demo: http://jsfiddle.net/Gdp6p/

Categories