I want the variable inputname to go up by 1 every time a new <input /> is added
e.g.
<input name="1" />
<input name="2" />
<input name="3" />
---html---
<p class="add">Add</p>
<div class="added"></div>
---jQuery/javascript---
$(document).ready(function() {
$("p.add").click(function() {
var inputname = somevar;
var added = "<input type=\"text\" name=\""+inputname+"\" />";
$("div.added").append(added);
});
});
here it is on jsfiddle.net if it helps -> http://jsfiddle.net/gamepreneur/54kzw/
Set inputname like this:
var inputname = $('.added input').length + 1;
This gets the total number of added inputs and increments by one, resulting in the new name.
Change the variable scope
Use this:
// declare your variable here so it exists throughout every call, instead of being
// delcared new with every call.
var inputname = somevar;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type=\"text\" name=\""+(inputname++)+"\" />";
$("div.added").append(added);
});
});
Alternatives:
Grab the number of inputs ($('div.added input').length) and use that for a counter.
Grab the id of the last item $('div.added input:last').prop('name')) and increment it.
You need to declare inputname in the global scope so that it lasts longer than just the duration of the click function and then you need to increment it each time you use it.
I modified your fiddle to this: http://jsfiddle.net/jfriend00/54kzw/2/
var inputname = 1;
$(document).ready(function() {
$("p.add").click(function() {
var added = "<input type='text' name='" + inputname++ + "' />";
$("div.added").append(added);
});
});
Try
$(document).ready(function() {
$("p.add").click(function() {
var inputname = $('input', $("div.added")).length + 1;
var added = "<input type=\"text\" name=\"" + inputname + "\" />";
$("div.added").append(added);
});
});
Consider adding some other selectors to choose those inputs (like a class selector)
Related
I have some js that adds an input field for a user:
var user = "O'Conner, John"
b.innerHTML += "<input type='hidden' value='" + user + "'>";
When its inserted it looks like this:
<input type="hidden" value="O" Conner, John'>
How do I amend this so it outputs like this:
<input type="hidden" value="O'Conner, John">
I need the value to show the full name with the apostrophe. How can I get this to work?
You can escape the value first by replacing it with HTML entities.
As for ' - It can either be ’ or ‘
var user = "O'Conner, John";
user = user.replace("'", "‘");
document.getElementById("container").innerHTML += "<input type='text' value='" + user + "'>";
<div id="container"></div>
There is also another thread that already answers this question.
When you create an element with JavaScript, you can pass the value to the input without any issue. Please check the below example:
var user = "O'Conner, John"
var b = document.getElementById("b")
var input = document.createElement("input")
input.type = "text"
input.value = user;
b.appendChild(input)
<body id="b"></body>
i am trying to create chkbox on click with different name and value and then alerting its value resulting in error "NaN" my script is here,
<script type="text/javascript">
var k=0,j=0;
$(document).ready(function () {
$("#btnAdd").click(function () {
var field = $("#field").val();
k+=1;
var newRow1="<tr><td align='center' style='font-size: large; color: #212121;' height='35px'>from"
+DDL_fromProfession +" to "+DDL_ToProfession +"</td></tr>"
+"<tr><td align='center' style='font-size:large;color:#212121;' height'35px'>"
+"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>I currently work here</input>";
alert(k);
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
alert(chkvalue);
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
var input = "<input name='parameters' id='field' type='text' />";
var input1="<input name='parametersCompany' id='field' type='text'/>"
var newRow = "<tr><td align='center' style='font-size: x-large; color: #212121;' height='35px'>"
+ input + " at " +input1 +"</td></tr>";
$('#controls').append(newRow);
$('#controls').append(newRow1);
});
});
</script>
i wanna crete chkbox like,
name = chkbx_CurrPro0 , value = 0
name = chkbx_CurrPro1 , value = 1
name = chkbx_CurrPro2 , value = 2
.
.
.
then i am printing its value resulting in NaN error ?? Hopes for your suggestion
one more thing i wanna do after creating dynamicaally chkbox it will get value of only marked chk box ,
my code here,
var checkBoxes = $("input[name=" + chkbx_CurrPro + "]");
$.each(checkBoxes, function() {
if ($(this).attr('checked')){
//do stuff
}
});
but check all chkbox created at run time
Hopes for Suggestions
Thanks
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro'"+k+"'']").val()) + 1;
I think you have some issues with the quotes here. Try this...
var chkvalue = parseInt($(":checkbox[name='chkbx_CurrPro"+k+"']").val()) + 1;
EDIT: Looks like youhave the same issue here...
"<input type='checkbox' name='chkbx_CurrPro'"+k+"'' value='"+k+"'>
This will try to make the name chkbx_CurrPro'1' but that is not valid. This should instead be...
"<input type='checkbox' name='chkbx_CurrPro"+k+"' value='"+k+"'>
Edited Again :
I see another issue here, you are trying to get the value of the checkbox before the checkbox has actually been added to the dom. You have added it to the string, but that is just a string of text when you call parseInt, not a part of the page. Move the parseInt line to below your append lines, near the bottom.
Hi this was actually orginally in another question (HERE) that had two parts. The first part was solved by #epascarello - thanks again, now just this part remaining, and i don't seem to get it.
I'm creating a duplicate-able div's containing checkboxes, on submit it only returns one value for the original input in the console, but no value for any duplicates.
Any help greatly appreciated.
JS Fiddle: http://jsfiddle.net/dawidvdh/EEd7c/
jQuery:
//Clone Tracking
var g_counter = 1;
var d_counter = 1;
var dependant = ["dependant"];
var group;
//Clone Tracking
//General Variables
var relation_input_groups = ["relation-group-1"];
//General Variables
//Generate variables
var relation_fields=[0];
var relation_input ="<label>Spouse</label>"+
"<input type='checkbox' value='spouse' class='relationship' name='relationship' />" +
"<label>own child</label>"+
"<input type='checkbox' value='ownchild' class='relationship' name='relationship' />" +
"<label>adopted</label>"+
"<input type='checkbox' value='adopted' class='relationship' name='relationship' />" +
"<label>stepchild</label>"+
"<input type='checkbox' value='stepchild' class='relationship' name='relationship' />" +
"<label>parent</label>"+
"<input type='checkbox' value='parent' class='relationship' name='relationship' />" +
"<label>inlaw</label>"+
"<input type='checkbox' value='inlaw' class='relationship' name='relationship' />" +
"<label>brother</label>"+
"<input type='checkbox' value='brother' class='relationship' name='relationship' />" +
"<label>other</label>"+
"<input type='checkbox' value='other' class='relationship' name='relationship' />";
//Generate variables
jQuery(document).ready(function(e) {
//populate jquery generated fields
jQuery(relation_fields).each(function() {
jQuery(relation_input).appendTo('#relation-group-1');
});
//populate jquery generated fields
//Cloning Function
jQuery('#clone').click(function() {
clone_dependant();
});
function clone_dependant() {
// Store the value of the previous Id to insert the cloned div..
var oldId = g_counter;
g_counter++;
currentdep ='dependant-'+g_counter;
// Clone the Dependant Div and set a new id
var $clonedDiv = jQuery('#dependant-1').clone(false).attr('id', 'dependant-'+g_counter);
var relation_newDiv = 'relation-group-'+ g_counter;
// Find div's inside the cloned object and set a new id's
$clonedDiv.find('#relation-group-1').attr('id',"relation-group-" + g_counter );
// You don't need to Loop thru the inputs to set the value
$clonedDiv.find('input').val('');
$clonedDiv.find('input:checkbox').removeAttr('checked');
// Insert the cloned object
$clonedDiv.insertAfter("#dependant-" + oldId);
relation_input_groups.push(relation_newDiv);
}
//Cloning Function
//Validation
//submit function
$(document).on("click", 'input[type="checkbox"]', function() {
jQuery(this).siblings(":checked").removeAttr('checked');
});
var result = {};
var dependants;
var dep_counter = 0;
jQuery('#submit').click(function(){
jQuery('.dependant').each(function(k, v){
dep_counter++
dependants = {};
result['dependant'+dep_counter] = [dependants];
dependants['relationship'] = $(v).find('.relationship:checked').val();
});
var jsonData = JSON.stringify(result);
console.log(jsonData);
});
});
and the HTML:
<div id="dependant-1" class="dependant">
<div id="label">relationship:</div> <div id="relation-group-1"></div>
</div>
<button id="clone">clone</button>
<button id="submit">submit</button>
See this updated fiddle : http://jsfiddle.net/EEd7c/7/
Comment this line : $clonedDiv.find('input').val('');
Also set dep_counter = 0; on submit button click..
Your cloned check boxes do not have any values assigned to it. Ensure that when its cloned the values are set in the net set of checkboxes
It is simply because those checkboxes have the same name attribute. When the submit button is pressed, it serializes the values of all the form controls (text boxes, radio boxes, check boxes, etc) and send them. The name property should be unique for all those controls.
In your code, all those checkboxes have the same name property (relationship) which makes them indistinguishable. A fix to this problem is to give different names to those check boxes.
<table border="0" class="commentbox">
<tr>
<td>
<div id="comment-f78d0b00-a008-473d-b647-a4a103ee3778"></div>
<input type="button" class='btnReply' id="reply-f78d0b00-a008-473d-b647-a4a103ee3778" value="Reply"/>
</td>
</tr>
</table>
$(".commentbox .btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).attr("id").split("-")[1]
alert(id);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' />
<input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
i want the f78d0b00-a008-473d-b647-a4a103ee3778 to come after split rather alert is giving
f78d0b00
I have tried to change id = comment_ f78d0b00-a008-473d-b647-a4a103ee3778 and split
id = $(this).attr("id").split("_")[1],but it doesnt work.
Edited
Input - container-f78d0b00-a008-473d-b647-a4a103ee3778
Output after split f78d0b00-a008-473d-b647-a4a103ee3778
A slightly convoluted means of achieving your end-result:
// splits the supplied string by the hyphen '-' character
var string = 'comment-f78d0b00-a008-473d-b647-a4a103ee3778'.split(/-/);
// removes the zeroeth/first element from the string array
string.shift();
// joins the remaining elements from the string back together
var newString = string.join('-');
console.log(newString);
JS Fiddle demo.
Edited to turn the above into a function:
function splitString(haystack, needle){
if (!needle || !haystack){
return false;
}
var string = haystack.split(needle);
string.shift();
return string.join(needle);
}
// the first argument is the string you want to work on,
// the second is the character you want to split on
// f is the variable that will hold the new string
var f = splitString('comment-f78d0b00-a008-473d-b647-a4a103ee3778','-');
console.log(f);
JS Fiddle demo.
References:
join().
shift().
split()
If the format of the string is not going to change then how bout using the substring function instead?
var str = "comment-f78d0b00-a008-473d-b647-a4a103ee3778";
var subStr = str.substring(str.indexOf("-") + 1);
alert(subStr);
This returns: f78d0b00-a008-473d-b647-a4a103ee3778
Here s a jsfiddle for the same
http://jsfiddle.net/M2Ywy/
If it works for you then your code would look like this
var id = $(this).attr("id");
var subStr = id.substring(str.indexOf("-") + 1);
alert(subStr);
var strDiv =
"<input type='text' class='txtCmnt' id='txtReply-" + id + "' /> <input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + subStr).append(strDiv);
Demo jsFiddle
This should do it:
var id = '';
var strDiv = '';
$(".btnReply").live("click", function () {
// $(this).hide();
// i = 1;
id = $(this).prev('div').attr("id").split("comment-")[1];
alert(id);
strDiv = "<input type='text' class='txtCmnt' id='txtReply-"+ id +"' /><input type='button' class='btnSave' value='Save' id='btnSave-"+ id +"' />";
$("div[id*="+id+"]").append(strDiv);
});
You can do it this way, might be a longer version, but just 3 lines strong.
Just split() the string via the hyphens "-" and then splice the first index and then rejoin the whole string using the join() method
example: http://jsfiddle.net/eE48z/
$(document).ready(function(){
$(".commentbox .btnReply").click(function(){
var jid = $(this).attr("id").split("-");
jid.splice(0,1);
var id=jid.join("-");
alert(id);
var strDiv = "<input type='text' class='txtCmnt' id='txtReply-" + id + "' /><input type='button' class='btnSave' value='Save' id='btnSave-" + id + "' /> ";
$("#comment-" + id).append(strDiv);
});
});
Can some one help me in this
I had a variable
var myValue = "what is you name? what is your age?"
i want to find the '?' in the string and replace it with a html input text element
where the user can enter the answer in the text box and at last i need a string as out put like this
"what is your name my name is xyz what is your age i am 25"
Please help me in this
Thanks
Kumar
This will dynamically take your myValue, replace all ?'s with inputs and then add a button to alert you of the user input. It will place myValue into the body, but you can place it somewhere else.
$(function() {
var myValue = "what is you name? what is your age?";
myValue = "<div>" + myValue;
while(myValue.indexOf("?") > -1)
myValue = myValue.replace("?", " <input type=\"text\" />");
myValue += "</div>" + "<button type=\"button\" onclick=\"sumUp(this)\">Declare</button>";
$("body").html(myValue);
});
function sumUp(button) {
var $prevDiv = $(button).prev().clone();
$prevDiv.children("input").each(function() {
$(this).replaceWith($(this).val());
});
alert($prevDiv.html());
}
If you have 2 input elements with IDs 'name' and 'age' respectively you can do this:
var nameValue = document.getElementById('name').value;
var ageValue = document.getElementById('age').value;
var anotherValue = myValue
.replace(/name\?/, nameValue)
.replace(/age\?/, ageValue)
You should be able to do something as simple as:
var myValue = "what is you name? what is your age?"
var nameVar = window.prompt("What is your name?","");
var ageVar = window.prompt("What is your age?","");
var myValue = myValue.replace("?", nameVar).replace("?", ageVar);
Alternatively, you could do something like:
var myValue = "what is you name? what is your age?"
var nameVar = '<input type="text" id="name" name="name">';
var ageVar = '<input type="text" id="age" name="age">';
document.write(myValue.replace("?", nameVar).replace("?", ageVar))
You'd then read the two input elements using jQuery with:
$('name').val();
$('age').val();
If you have a div with the question in it:
<div id="questions">What is your name? What is your age?</div>
and you want to replace those ? marks with input boxes, you could do this to make input boxes show up right after the questions:
var questions = $("#questions").text();
var questionMarkIndex = questions.indexOf("?");
var nameQuestion = questions.substring(0, questionMarkIndex+1);
var finalHtml = nameQuestion + '<input id="name" type="text" />';
var ageQuestion = questions.substring(questionMarkIndex+1);
finalHtml += ageQuestion + '<input id="age" type="text" />';
$("#questions").html(finalHtml);
This (or something close to it) will make you end up with What is your name?[input box] What is your age?[input box].