How to synchronize every pair of dynamically created inputs? - javascript

I'm creating dynamically multiple elements and i want to synchronize specific ones. I write this code to give a view of my problem as simple as i can.
After creating input and append his value i want to have possibility to edit it every time i want.
So if i create multiple iputs of id input0,1,2 etc. and change value of specific one i want to get this value in suitable input. I write function for 1 pair, How can i achieve that for every pair of dynamically created inputs?
$(document).ready(function() {
var a = 0;
$('#add').hide();
$('#generateInput').click(function() {
$('#divArea').append('<input name="input' + a + '">');
$('#generateInput').toggle();
$('#add').toggle();
})
$('#add').click(function() {
$('#divArea').append('<input name="copyInput' + a + '" value="' + $('input[name="input' + a + '"]').val() + '"readonly="readonly"><br />');
$('#add,#generateInput').toggle();
a++;
})
});
//how to make this for all created inputs?
$(document).on('keyup', '[name="input0"]', function() {
$('[name="copyInput0"]').val(this.value);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="divArea"></div>
<button id="generateInput">Generate</button>
<button id="add">Add</button>

You can simply use the onkeyup() for each input you create and get the value inside that function.
var a = 0;
$(document).ready(function() {
$('#add').hide();
$('#generateInput').click(function() {
$('#divArea').append('<input onkeyup="onKeyUp(this)" name="input' + a + '" index="' + a + '">');
$('#generateInput').toggle();
$('#add').toggle();
})
$('#add').click(function() {
$('#divArea').append('<input name="copyInput' + a + '" value="' + $('input[name="input' + a + '"]').val() + '"readonly="readonly"><br />');
$('#add,#generateInput').toggle();
a++;
})
});
//how to make this for all created inputs?
function onKeyUp(input) {
$('input[name="copyInput' + $(input).attr('index') + '"]').val(input.value)
}
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<div id="divArea">
</div>
<button id="generateInput">
Generate
</button>
<button id="add">
Add
</button>

Related

Find all div's beginning with id="string", iterate through result and change their id's

I have a button which creates div's with numbered id's (div0, div1, div2). Each div contains a button to delete the div. The buttons are also numberes (delete_div0, delete_div1, delete_div2).
After delete e.g. div0, I want to reorganize everything so it starts from 0 again (in this case div1 -> div0 and div2 -> div1.
Another example: Delete div1, div0 -> div0, div2 -> div1.
Any help?
var counter_div = 0;
$("#add_div").click(() => {
$("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>");
//add listener
$("#delete_div" + counter_div).click((event) => {
nr = event.target.id.substring(
event.target.id.length - 1,
event.target.id.length
);
$("#div" + nr).remove();
})
// this is where I am struggling reorganizing divs
function reorganize() {
$("div[id^=div]").each((element) => {
$(this).prop("id", "div" + element);
});
}
reorganize();
counter_div++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add_div' type='button'>Add div</button></div>
<div id='divs'></div>
EDIT:
Thanks to everbody, I found a mix out of every solution.
$("#delete_div" + counter_div).click((event) => {
//remove div
$(event.currentTarget).parent().remove();
//reorder all ingredients
$("div[id^=div]").each((element) => {
$(this)
.find("div[id^='div']")
.eq(element)
.prop("id", "div" + element);
};
});
Probalby not the most beautiful solution, but it works. What I did not understand yet is why $(this) in the each-function gives different results depending on which syntax I use.
$("div[id^=div]").each(function(element) {console.log($(this))};
is different to
$("div[id^=div]").each((element) => {console.log($(this))};
You can perform delete with $(event.currentTarget).parent().remove();.
Similarly if you want to select any input from on such button click you can use $(event.currentTarget).parent().find("input").
Or you want to loop over divs and find all inputs then you can use :
$('#divs > div[id^=div]').each(function(k) {
var allInputs = $(this).find('input');
});
var counter_div = 0;
$("#add_div").click(() => {
$("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>");
//add listener
$("#delete_div" + counter_div).click((event) => {
$(event.currentTarget).parent().remove();
})
counter_div++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add_div' type='button'>Add div</button></div>
<div id='divs'></div>
First call your reorganize on remove
$("#div" + nr).remove();
reorganize();
})
then:
var numDivsNum=-1;
//set first id -1
function reorganize() {
[...document.querySelectorAll("#divs > div[id^='div']")].forEach(el => {
el.id="div"+(++numDivsNum);
// for each element add new id +1
el.innerHTML=el.innerHTML + "New id= " +numDivsNum;
});
}
And your selector was wrong, it should be:
div[id^='div']
not
div[id^=div]
var counter_div = 0;
$("#add_div").click(() => {
$("#divs").append("<div id='div" + counter_div + "'>Div " + counter_div + " <button id='delete_div" + counter_div + "' type='button'>X</button></div>");
//add listener
$("#delete_div" + counter_div).click((event) => {
nr = event.target.id.substring(
event.target.id.length - 1,
event.target.id.length
);
$("#div" + nr).remove();
reorganize();
})
// this is where I am struggling reorganizing divs
var numDivsNum=-1;
function reorganize() {
[...document.querySelectorAll("#divs > div[id^='div']")].forEach(el => {
el.id="div"+(++numDivsNum);
el.innerHTML=el.innerHTML + "New id is id='div" +numDivsNum+"'";
});
}
counter_div++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='add_div' type='button'>Add div</button></div>
<div id='divs'></div>
You can re-index them like this:
$('div[id^="div"]').each(function(k) {
$(this).prop('id', 'div' + k);
});
But personally I'd give them all a class so you don't have to rely on the begins with div selector, and then consider using data-id instead of id. data-id will be easier to extract as an integer later and that appears to be your goal. Maybe something like this?
$('div.my_class').each(function(k) {
$(this).data('id', k);
});
$("#delete_div" + counter_div).click((event) => {
//remove div
$(event.currentTarget).parent().remove();
//reorder all ingredients
$("div[id^=div]").each((element) => {
$(this)
.find("div[id^='div']")
.eq(element)
.prop("id", "div" + element);
};
});
You have almost done
But there are some stuff that needs to be fixed
$(this).parent('div').eq(0).remove();

Want to add delete functions for a list of date displayed

to summarize my problem ... I have made a calendar with contains the from - to date range. Now the selected dates are displayed in a div with a delete button for each. But as the id of the button is the same for all the dates ....it deletes the entire date range. I have attached the screenshot as well.
I also tried taking a loop and giving each date a div so that the Del function will work properly. but I wasn't successful. I will mention code for the same
$(document).ready(function () {
var i = 0;
$.each(between, function (key, value) {
var rest = $('#target').append($('<div id="r' + i +value+ '" class="ansbox">
</div>'));
console.log(between);
var template = '<div id="ChildTarget_' + i + '"><span>key + ":" + "' + value + '"
</span><button id="tr' + i + '" class="target">X</button></div><br></div>';
i++;
$('#target').on('click', function () {
console.log("hola");
$('#target').remove();
You should add click event for the button itself.
var template = `
<div id="ChildTarget_' + i + '">
<span>key + ":" + "' + value + '"</span>
<button id="tr' + i + '" class="deleteButton">X</button>
</div>`;
$(".deleteButton').on('click', function() {
// do deletion here
});
First of all ,
The 'X' button should have different id
$.each(between, function (key, value){
$('#results').append(key+":"+value+'<br>');
$('#results').html(between.join('<button id="result"+key+"" > X </button><br>')
here you can see i am adding key to the Button Id making it unique. Use that id to remove the value, that you dont want. Hope this helps

How to add new row to the table using a button in mvc4 view

I'm trying to add a button to 'add new row' to the table in my mvc view.
First I tried this and it worked.
<script type="text/javascript">
$(document).ready(function () {
function addRow() {
var html = '<tr><td>' +
'<input type="text" id="Text1">' +
'</td><td>' +
'<input type="text" id="Text2">' +
'</td></tr>'
$(html).appendTo($("#table1 > tbody"))
};
$(".BtnAdd").click(addRow);
});
</script>
Then I had to change input type="text" to #Html.TextAreaFor()
So I tried this...but not working
<script type="text/javascript">
$(document).ready(function () {
function addRow() {
var html = '<tr><td>' +
'#Html.TextAreaFor(m => m.schedule1)' +
'</td><td>' +
'#Html.TextAreaFor(m => m.Schedule2)' +
'</td></tr>' +
$(html).appendTo($("#table1 > tbody"))
};
$(".BtnAdd").click(addRow);
});
</script>
Anyone please help me...Sorry if my way of presenting the problem is bad (new to .net)
Is there any other good way? (using for each loop etc)
Thanks

jquery each loop write data for each div

I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;

JQuery UnBind Works, Attempt to "re" bind does not

I'm working my way through a JQuery Solution and for the most part it works but I"m stumped on seemingly a small detail I know I'm overlooking. Heck, maybe my implementation/approach needs to be reconsidered.
Here's the flow of what works.
1. Click an anchor that adds to a table.
2. Add CSS Class.
3. Disable (Unbind) click on after preappend().
4. From the table of dynamically added record remove table based on ID.
5. delete class that was added in step 2.
6. Bind 'click'
However, although I can bind the click and alert on it. The expected functionality does not allow me to step through the above process again.
The code in question:
HTML SAMPLE:
link that starts the process:
table that holds new records after click of link
<table id="carrier-table"><tbody></tbody></table>
JQUERY and Custom Javascript Function
<script type="text/javascript" id="removeCarrier">
function removeCarrierFromList(obj) {
var i = obj.parentNode.parentNode.rowIndex;
document.getElementById('carrier-table').deleteRow(i);
$('a#' + obj.id).removeClass('delete-carrier-company');
//alert(obj.id); //.hasClass('add-carrier-company').tostring() ); //
$('a#' + obj.id).bind('click', function() {
//alert('User clicked on ' + obj.id);
});
}
</script>
<script type="text/javascript" id="carrierListJS">
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(
function() {
var target = $(this).attr("id");
alert(target);
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" +
"<td><a href='#' id='" + target + "' class='delete' onclick='removeCarrierFromList(this)'> </a></td>" +
"<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" +
"</tr>");
return false;
});
$('.add-carrier-company').click(
function() { $(this).addClass('delete-carrier-company').unbind('click'); }
);
});
</script>
There were a few issues I noticed with the code. For one thing, as #RussellUresti mentioned, you create two tags with the same ID. For another thing, if you're using ID's in a selector in jQuery, don't include the tag name, just use the id (ie. use $('#id') not $('a#id')) it will be faster (it won't break your code though).
I have created a jsfiddle to answer your question (though I rewrote most of it). :) I think it's what you're looking for.
Here's the code:
Test HTML
aa
bb
cc
10002
10003
<table id="carrier-table" style="border:1px solid #000"><tbody></tbody></table>
JavaScript
function addCarrier() {
var target = $(this).attr("id");
$("#carrier-table").prepend("<tr id='carrierRow_" + target + "'>" + "<td><a href='#' id='a" + target + "' class='delete'> </a></td>" + "<td class='carrier-list-text'>" + target + " " + $("#name_" + target).val() + "</td>" + "</tr>");
$('#a' + target).click(removeCarrierFromList);
$(this).addClass('delete-carrier-company').unbind('click');
return false;
}
function removeCarrierFromList() {
var $this = $(this);
var id = $this.attr('id').replace("a","");
$this.closest('tr').remove();
$('#' + id).removeClass('delete-carrier-company').click(addCarrier);
}
$(function() {
// Link
// This adds a carrier to a list
$('.add-carrier-company').click(addCarrier);
});

Categories

Resources