Selecting ID's dynamically in js/ JQuery - javascript

I have an html form. Whenever i click add button another copy of it appends. Whenever i click add button, id of my elements increases such as username_0, username_1, username_2... There are 2 radio buttons on my form that whenever i choose second radio button, a hidden textarea appears. Problem is i'm having problem with choosing my dynamic id's of radio buttons. I made a function but its only working for first element since i can't get dynamic id's
<label for="evetKontrol_0">Evet</label>
<input type="radio" id="evetKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygun" checked>
<label for="hayirKontrol_0">Hayır</label>
<input type="radio" id="hayirKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygunDegil">
<div id="ifNo_0" style="visibility:hidden">
<strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_0" name="hayirSebep" style="height: 75px"><br>
</div>
function yesnoCheck() {
if (document.getElementById('evetKontrol_0').checked) {
document.getElementById('ifNo_0').style.visibility = 'hidden';
}
else document.getElementById('ifNo_0').style.visibility = 'visible';
}
I need to be able to get my evetKontrol_#somenumber for my function for every copy of my form.
JSfiddle/ all of my code
I tried to use jQuery( "[attribute*='value']" ) but i couldn't manage to work it out.

Consider the following.
Working Example: https://jsfiddle.net/Twisty/sonvakq2/21/
JavaScript
$(function() {
function addElement(tObj) {
var counter = $("[id^='ogrenci']", tObj).length;
var html = '<div class="col-auto" id="ogrenci_' + counter + '"><label for="ad">Ad</label><input type="text" name="ad[]" class="form-control" id="ad_' + counter + '" placeholder="Öğrencinin Adı"/><label for="soyad">Soyad</label><input type="text" name="soyad[]" class="form-control" id="soyad_' + counter + '" placeholder="Öğrencinin Soyadı"/><label for="no">No</label><input type="text" name="numara[]" class="form-control" id="no_' + counter + '" placeholder="Öğrencinin Numarası"><label for="course">Bölümü</label><input type="text" name="bolum[]" class="form-control" id="course_' + counter + '" placeholder="Öğrencinin Bölümü"><label for="alKredi">Almak İstediği Kredi</label><input type="text" name="alKredi[]" class="form-control" id="alKredi_' + counter + '" placeholder="Almak İstediği Kredi"><label for="verKredi">Alabileceği Kredi</label><input type="text" name="verKredi[]" class="form-control" id="verKredi_' + counter + '" placeholder="Alabileceği Kredi"><label for=""><strong>Uygun mu?</strong> </label><br><label for="evetKontrol_' + counter + '">Evet</label><input type="radio" id="evetKontrol_' + counter + '" name="uygun_' + counter + '" value="uygun" checked><label for="hayirKontrol_' + counter + '">Hayır</label><input type="radio" id="hayirKontrol_' + counter + '" name="uygun_' + counter + '" value="uygunDegil"><div id="ifNo_' + counter + '" style="visibility:hidden"><strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_' + counter + '" name="hayirSebep" style="height: 75px"><br></div><div class="input-group-addon"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</div></div>';
tObj.append(html);
}
function showHidden() {
$("[id^='evetKontrol']").each(function(i, el) {
var rel = $("#ifNo_" + i);
if ($(el).is(":checked")) {
rel.show();
} else {
rel.hide();
}
});
}
//add more fields group
$("#add").click(function() {
addElement($("#container"));
});
//remove fields group
$('#container').on('click', "a[id^='remove']", function() {
$(this).parents('div.col-auto').remove();
});
$("#container").on("click", "input[type='radio']", showHidden);
});
Your fiddle wasn't configured properly, so I addressed that first. I moved a lot of the repeatable items into Functions. Switched it all the jQuery and removed any of the local javascript calls.
You can see examples of how to use the Attribute selector in a relative manner to select items you want.
See More: https://api.jquery.com/category/selectors/attribute-selectors/

You shouldn't need to use IDs for this. Just capture the onclick event and pass a boolean to determine if the hidden input should be shown. If you have multiple inputs to show and hide separately, you could pass the ID of the input along with the boolean.
function yesnoCheck(show) {
var ta = document.getElementById('hiddenTA');
if (show) {
ta.style.visibility = 'visible';
} else {
ta.style.visibility = 'hidden';
}
}
<label for="user1_0">User 1</label>
<input type="radio" name="users" id="user1_0" onclick="yesnoCheck(false)" checked />
<label for="user2_0">User 2</label>
<input type="radio" name="users" id="user2_0" onclick="yesnoCheck(true)" />
<input style="visibility:hidden" id="hiddenTA" />

In order to get the evetKontrol_#somenumber, pass that number in the onclick function.
In your JSfiddle, this would mean concatenating the counter variable into the function parameters like
... onclick="javascript:yesnoCheck(' + counter + ');" ...
Then update the function to use that value:
function yesnoCheck(counter) {
if (document.getElementById('evetKontrol_' + counter).checked) {
document.getElementById('ifNo_' + counter).style.visibility = 'hidden';
} else {
document.getElementById('ifNo_' + counter).style.visibility = 'visible';
}

Related

Adding div on click only once and allowing customer to delete it and reclick it

I'm trying to make a button that when clicked displays only one div. If the user chooses they can click on the remove button and the data in any fields will be cleared and the text inside the div deleted. If a user chooses they can click the button again to bring back the div but cannot create the div more than once. I can make the initial div appear like its suppose to but beyond that I'm stuck.
Here is a list of things I've tried
$(document).on('click', '.remove', function(){
$document.getElementById("demo") .remove('.innerHTML');
$(document).on('click', '.empty', function(){
$('#demo').empty();
});
});
var count = 0;
function myFunction() {
document.getElementById("demo").innerHTML = '<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>';
}
$(document).on('click', '.empty', function() {
$('#demo').empty();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Add Renters</button>
<p id="demo"></p>
</body>
</html>
You're close check those steps to achieve what you want :
Add type="button" to your button to prevent the submit when you click.
Remove the inline onClick attribute and attach the click event from the JS code.
Check inside myFunction() function if the demo is empty or not before adding the content.
Attach another click event using event delegation on() (since the element was added dynamically to the DOM) to the button with .remove class to remove the content.
NOTE : Since you're using jQuery prevent the mix with vanillaJS like this line :
document.getElementById("demo").innerHTML = ...
Will be better to be :
demo.html(...)
$('button').on('click', myFunction);
$('body').on('click', '.remove', function() {
$('#demo').empty();
});
function myFunction() {
var demo = $('#demo');
if (!demo.html().length) {
demo.html('<div id="formwrap2" class="test' + count + '" name="test' + count + '"><div id="ddd"><div id="driverinfo">Renters Info<button type="button" name="remove" id="test2" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">Remove Renters</span></button></div><div id="formwrap"><div id="ftx1">APT OR UNIT:</div><section class="plan cf"><input type="radio" name="aptorunit' + count + '" id="Apt' + count + '" value="Apt"><label class="free-label four col" for="Apt' + count + '">Apt</label><input type="radio" name="aptorunit' + count + '" id="Unit' + count + '" value="Unit" ><label class="basic-label four col" for="Unit' + count + '">Unit</label></section></div><div id="formwrap"><div id="ftx1">COVERAGE :</div> <input type="text" id="addy" name="propcover" size="" maxlength="15" placeholder="10k to 100k"/></div></div><br><br><br></div>');
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<body>
<button type="button">Add Renters</button>
<p id="demo"></p>
</body>
</html>

How to reset the error number when deleted from list

I'm creating a set of textboxes and some drop downs using jQuery. The add function is working with out any issues.
My problem is with the delete function function works nicely as long as the user deletes one after the other but if the user delete from some where else the number sequence get messed up. Which breaks the 1,2,3,4 ... etc and sets the number which was deleted last.
As an example if the user deletes number 4 out of 7 errors the functions sets the last number as 4 when the user clicks the add button the next number generated will be 5 not the correct last number. I want to rest the rest of the numbers when something get removed from the middle.
I'm storing the last number in a hidden filed called stValue which is getting reset when deleting.
My problem is here I can't get my head around to think of way to reset this when deleting from some where else and then reset the entire error number row numbers when something get removed from the middle. Can you guys help me with this below is my code.
jsFiddle will help to understand better
JQuery:
//Add and remove function for the error text boxes
$(document).ready(function () {
$(document).on('click','.addRow',function () {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/);//Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_'+btnId).prop("disabled", true);//Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function () {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
alert(errNoList);
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_'+errNoList).prop('disabled',false);// Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
});
});
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1)+2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="'+genNum+'" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_'+genNum+'" data-bid="addRow_'+genNum+'" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_'+genNum+'" data-bid="delRow_'+genNum+'" value="Delete"/><br />'
}
HTML:
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%"/>
<input type="hidden" value="1" id="stValue"/>
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add"/>
</div>
</div>
</div>
**UPDATE:**Completely changed the code now it's much more simpler adding the solved answer here so it might help some one in the future.
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var btnId = $("#stValue").val(); //Read the value of stValue
btnId = btnId - 1; //Deduct 1 from the value to get the last ID
//Enables the 1st add button if the value equals 1
if (btnId === 1) {
$('#addRow_' + btnId).prop('disabled', false);
}
$(this).parent().remove(); //Remove the text row from the list.
resetErrorNo(); //Calls the reset function
});
});
//Reset the entire error count number index
function resetErrorNo() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
$("#stValue").val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>
Try with whenever, you delete any row, update all input with new number.
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
Full Code
//Add and remove function for the error text boxes
$(document).ready(function() {
$(document).on('click', '.addRow', function() {
var div = $("<div />"),
btnId = $(this).data("bid").match(/\d+/); //Breaks the number from the ID using .match
div.html(copy()); //Creates a new div container
$('.error-Column').append(div); //Insert all the HTML into the new div
$('#addRow_' + btnId).prop("disabled", true); //Disables the add button once clicked.
});
//Remove the text filed from the list and resets the error number
$(document).on('click', '.delRow', function() {
var //btnId = $(this).data("bid").match(/\d+/),//Breaks the number from the ID using .match
maxNoList = $('input[class="addRow"]').length,
errNoList = maxNoList - 1;
//btnId = btnId - 1; //Calculates the ID number of the previous button
$('#addRow_' + errNoList).prop('disabled', false); // Enables the previous add button
$('#stValue').val(errNoList); //Set the value of stValue when removing the text filed
//So the error numbers will be generated accordingly when Add is clicked again.
$(this).parent().remove(); //Remove the text row from the list.
rearrange();
});
});
function rearrange() {
$(".errorCount").each(function(index, _this) {
$(this).val(index + 1);
});
}
//HTML function which will be called by the button click event for the add button
function copy() {
var stNum = document.getElementById("stValue"),
genNum = (document.getElementById("stValue").value - 1) + 2;
stNum.value = genNum;
// language=HTML
return '<input class="errorCount" size="1" value="' + genNum + '" style="margin-left: 2%" readonly/>\n' +
'<select class="errorName" style="margin-left: 6%">\n' +
'<option selected disabled>----- Select Error -----</option>\n' +
'</select>\n' +
'<input type="button" class="addRow" id="addRow_' + genNum + '" data-bid="addRow_' + genNum + '" value="Add" />\n' +
'<input type="button" class="delRow" id="delRow_' + genNum + '" data-bid="delRow_' + genNum + '" value="Delete"/><br />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="jType-container">
<div id="error-Add-Container">
<div id="error-Column-Headings">
Error Number<span style="margin-left: 8%">Error Name</span>
</div>
<div class="error-Column">
<input class="errorCount" size="1" value="1" style="margin-left: 2%" />
<input type="hidden" value="1" id="stValue" />
<select class="errorName" style="margin-left: 6%">
<option selected disabled>----- Select Error -----</option>
</select>
<input type="button" data-bid="addRow_1" id="addRow_1" class="addRow" value="Add" />
</div>
</div>
</div>

Remove input field with span

I written this code for creating new input fields, and i need to somehow modify it so i can remove the fields. I tought about adding var counter to mySpan and then i make$(#removeBox).click(function() and there i can get an id of the input field i need to delete. But i cannot make span clickable, and when I try to do it with like this <a class="deleteBox' + counter'"><span class="glyphicon glyphicon-remove"></span></a> It says that I am missing ). I know there are some solutions on this problem here, but i wanted to make mine work.
var counter = 2;
$("#addTextField").click(function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<input type="text" name="textbox' + counter + '" placeholder="Category" /><span id="mySpan" class="glyphicon glyphicon-remove"></span>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
try like this: The trick is to remove the element you clicked on which you can get with $(this) inside the click
var counter = 0;
$("#addTextField").on('click', function() {
var newTextBoxDiv = $(document.createElement('div')).attr("id", 'textboxdiv'+counter);
newTextBoxDiv.after().html('<div class="wrapper">' + counter + '<input type="text" name="textbox' + counter + '" placeholder="Category" /><span class="glyphicon glyphicon-remove">remove</span></div>');
newTextBoxDiv.appendTo("#textboxgroup");
counter++;
});
$('body').on('click', '.glyphicon-remove', function(){
$(this).closest('.wrapper').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="addTextField">click to add</div>
<div id="textboxgroup"></div>
In your code you added an ID <span id="mySpan" on every click which is bad cause an ID should always be unique. So if you add it more than once it is not unique anymore. Better use classes instead...
try this:
var counter = 0;
$('#add').click(function() {
$('#target').append('<span>New Input: <input type="text"><button id="remove' + counter + '">Remove</button><br></span>');
$('#remove' + counter).click(function() {
$(this).parent().html('');
counter--;
});
counter++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<button id="add">Add</button>
<div id="target"></div>

jQuery Dynamic Add Form Field, Remove Form Field

Hello I am trying to add new form field and delete form field after getting inspired from this tutorial - http://bootsnipp.com/snipps/dynamic-form-fields
My Current Problem is to delete and reset the value of all in chronological order.
<input type="hidden" name="count" value="1" />
<div class="control-group" id="fields">
<label class="control-label" for="field1">Nice Multiple Form Fields</label>
<div class="controls" id="profs">
<div class="input-append">
<input autocomplete="off" class="span3" id="field1" name="prof1" type="text" placeholder="Type something (it has typeahead too)" data-provide="typeahead" data-items="8"
data-source='["Aardvark","Beatlejuice","Capricorn","Deathmaul","Epic"]'/><button id="b1" onClick="addFormField()" class="btn btn-info" type="button">+</button>
</div>
<br /><small>Press + to add another form field :)</small>
</div>
</div>
Javascript :-
var next = 1;
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b1" onClick="$(this).parent().remove();" class="btn btn-info" type="button">+</button>';
var newInput = $(newIn);
$(addto).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
Parent Element is getting removed, but next counter is not reset properly. in hidden and all new created form :-
Only Add Demo :- http://bootsnipp.com/snipps/dynamic-form-fields
Add an Delete Demo with Bug :- http://jsfiddle.net/6dCrT/2/
Can someone help me please.
Thanks
Try:
function addFormField(){
var addto = "#field" + next;
next = next + 1;
var newIn = '<br /><br /><input autocomplete="off" class="span3" id="field' + next + '" name="field' + next + '" type="text" data-provide="typeahead" data-items="8"><button id="b'+next+'" onClick="$(this).prev().remove();$(this).remove();" class="btn btn-info" type="button">-</button>';
var newInput = $(newIn);
console.log(addto);
$(addto).after(newInput);
if(next>1)
$("button#b"+next).after(newInput);
$("#field" + next).attr('data-source',$(addto).attr('data-source'));
$("#count").val(next);
}
DEMO FIDDLE
In my example, I was building a form that would allow users to add multiple input names if they had more than one dog.
var counter = 0
jQuery(function () {
$(".newDog").click(function(){
counter ++;
if (counter < 4) {
var elem = $("<input/>",{
type: "text",
name: `dogname${counter}`
});
} else {
alert("You can only add 4 Dog Names")
}
var removeLink = $("<span/>").html("X").click(function(){
$(elem).remove();
$(this).remove();
counter --;
});
$(".dogname-inputs").append(elem).append(removeLink);
});
})
Full credit as mentioned to https://stackoverflow.com/users/714969/kevin-bowersox

asp.net mvc and javascript textbox issue

I have a problem with the TextBox. When I was entering duplicate data, it is not allowing. That is what exactly I need but after saving data again it is allowing the duplicate data. How can I handle the scenario?
Here is my code.
var Controls = {
saveObjectives: function (actionurl) {
var frm = $('form[name=frmObjectives]')
frm.attr('action', actionurl);
frm.submit();
},
addObjectiveCheckbox: function () {
var text = $('#txtObjective').val();
$('#txtObjective').val('');
if ($.trim(text) == '')
return;
if ($('input[type=checkbox][value="' + text + '"]').length == 0)
$('#dvObjectives').prepend('<input type="checkbox" name="chkNewobjectives" value="' + text + '" Checked /> ' + text + '<br />');
},
And my HTML code is:
<input id="btnAddObj" class="btn" type="button" onclick="Controls.addObjectiveCheckbox();" value="Add Objective"/>
</div>
<div id="dvObjectives" name="ObjectivesList">
#foreach (Andromeda.Core.Entities.Objectives objective in Model)
{
<label class="checkbox">
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveID" />#objective.ObjectiveText
</label>
}
</div>
You are using value='whatever text` in the jQuery, but value='ObjectiveID' in the view. This should fix it:
<input type="checkbox" name="chkobjectives" Checked value="#objective.ObjectiveText" />#objective.ObjectiveText

Categories