jQuery add and remove textbox Add all Previews textbox - javascript

This is my jQuery add and remove textbox task, I just want to add my previous all textbox on Add Button. So if I will click first time it will add only 1 and if I will click again it will add 2nd textbox and if I will click again it will add 3rd textbox for me. I want just count the counter variable and then add +2 textbox in it.
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
div {
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h1>jQuery add / remove textbox example</h1>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

If I understand you want the number of input in creation to be always even number .
so simple just check the $("#TextBoxesGroup input").length % 2 wether it's 0 or 1 and create inputs using loop , (this last will create one or input at same time )
See below snippet :
$(document).ready(function() {
var counter = 2;
$("#addButton").click(function() {
if (counter > 10) {
alert("Only 10 textboxes allow");
return false;
}
var num_to_create = 0;
$("#TextBoxesGroup input").length%2 === 0 ? num_to_create = 2 : num_to_create = 1;
for(var inc=0 ; inc < num_to_create; inc++) {
var newTextBoxDiv = $('<div>')
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #' + counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="textbox' + counter + '" value="" >');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
}
});
$("#removeButton").click(function() {
if (counter == 1) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function() {
var msg = '';
for (i = 1; i < counter; i++) {
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
div {
padding: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<h1>jQuery add / remove textbox example</h1>
<div id='TextBoxesGroup'>
<div id="TextBoxDiv1">
<label>Textbox #1 : </label><input type='textbox' id='textbox1'>
</div>
</div>
<input type='button' value='Add Button' id='addButton'>
<input type='button' value='Remove Button' id='removeButton'>
<input type='button' value='Get TextBox Value' id='getButtonValue'>

Related

Problem in writing a razor code in Script

This is my code. I want to create two textboxes using Razor in script.
the model=>model[i].Name1 is not woring
var counter = 0;
#{
int i = 0;
}
$(document).ready(function () {
$("#addButton").click(function () {
if (counter < 0) {
alert("Add more textbox");
return false;
}
i = counter;
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter).attr("class", 'TextBoxDiv').attr("style", "border:5px solid green");
newTextBoxDiv.after().html('<label>Name #'+ counter + ': </label>' +
'#Html.EditorFor(model => model[i].Name1);' +
'<br/> <label>Email #'+ counter +': </label>' +
'#Html.EditorFor(model => model[i].EmailID);' +
'<br/><input type="button" name="button' + counter +
'" class="removeButton" id="removeButton' + counter + '" value="Remove Button" onclick="remove(this)">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
alert(i.toString());
counter++;
i = i + 1;
});
});
You cannot get JS to write out Razor - the JS happens client side AFTER the razor has been executed on the server and sent to the client. the JS won't know what to do with the razor syntax.
In this case, you would need to manually create the html which the Razor helper would make for you. It should still parse back into razor, providing you put the html in the right format (right name, id etc)
So write out the and make the name field match what the razor would have generated.
You can try to set a js variable with the value of model,and then use <input/> to replace #Html.EditorFor():
var counter = 0;
var m = JSON.parse('#Json.Serialize(#Model)');
$(document).ready(function () {
$("#addButton").click(function () {
if (counter < 0) {
alert("Add more textbox");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter).attr("class", 'TextBoxDiv').attr("style", "border:5px solid green");
newTextBoxDiv.after().html('<label>Name #'+ counter + ': </label>' +
'<input id="model_' + counter +'__Name1" name=" model[' + counter + '].Name1" value="' + m[counter].Name1 + '"/>' +
'<br/> <label>Email #'+ counter +': </label>' +
'<input id="model_' + counter +'EmailID" name=" model[' + counter + '].EmailID" value="' + m[counter].EmailID + '"/>' +
'<br/><input type="button" name="button' + counter +
'" class="removeButton" id="removeButton' + counter + '" value="Remove Button" onclick="remove(this)">');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
});

Add values in dynamic inputs using Jquery

With the help of http://www.mkyong.com/wp-content/uploads/jQuery/jQuery-add-remove-textbox.html , I got my dynamic inputs and value.
But while adding its concatenating or getting Nan. I need to add values.
var counter = 2;
$("#addButton").click(function () {
if(counter>20){
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html(
' <div class="col-md-6 marg-top-10 "> <input type="text" class="form-control inputData" name="assetDescription' + counter +
'" id="assetDescription' + counter + '" value="" > </input> </div>' +
' <div class="col-md-6 marg-top-10 "> <input type="text" class="form-control inputData" name="textbox' + counter +
'" id="textbox' + counter + '" value="" > </input> </div>'
);
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
for adding value
$("#getButtonValue").click(function () {
console.log("came ");
var msg = '';
var totalvalue;
var result;
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
result += Number($('#textbox' + i).val());
console.log(result);
}
result is = Nan
help please!
try with this..
var result = 0;
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
result += Number($('#textbox' + i).val());
console.log(result);
}

Javascript dynamic array window with multiple answer options

I'm working on multiple arrays and occured to one problem.
When I have only one question div generated I can add additional questions without problem, but if I add another question div, I can't add additional questions to neither of both windows(same applies to any other number too), error which is I get is newdiv[counterq] is undefined. Can anybody help me with this issue? Thanks!
Also, how can I move div AddOption below created new one option input?
I'm new at programming sorry if won't explain in correct terms. Thanks!
Edit: Updated with new problem. Didn't wanted to create seperate topic.
HTML :
var counterq = 0;
var limitq = 3;
var countero = 0;
var limito = 5;
function AddContent(divName) {
countero = 0;
if (counterq == limitq) {
alert("You have reached the limit of adding " + counterq + " inputs");
} else {
var newdiv = new Array()
newdiv[counterq] = document.createElement('div');
newdiv[counterq].className = "ContentWindow[" + counterq + "]";
newdiv[counterq].innerHTML = "<p class='ContentQuestion'>Question " + (counterq + 1) + " </p> <input type='text' class='AddQuestionInput' value='Type your question' name='myQuestion[" + counterq + "]'>";
if (countero == limito) {
alert("You have reached the limit of adding " + countero + " options");
} else {
newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 1) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + countero + "]'></div>";
newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 2) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + (countero+1) + "]'></div>";
document.getElementById(divName).appendChild(newdiv[counterq]);
countero += 2;
AddOption = function() {
var counterq = 0;
var limito = 5;
if (countero == limito) {
alert("You have reached the limit of adding " + countero + " options");
} else {
newdiv[counterq].innerHTML += "<div class='OptionInputOuterWindow'><span class='OptionInputDescription'>Option " + (countero + 1) + "</span> <input type='text' class='AddOptionInput' name='myQuestion[" + counterq + "]"+"[myInputs]"+"[" + countero + "]'></div>";
$("div[class*=ContentWindow]").css("height", "+=27");
countero++;
}
};
}
$(".container").css("height", "+=344");
newdiv[counterq].innerHTML += "<div class='AddOption' onclick='AddOption();'><img src='/img/Plussmall.png'>Add option</div>";
counterq++;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Content"></div>
<div class="AddContent" onclick="AddContent('Content');" >
<img src="/img/Plussmall.png">Add content
</div>
If you want the counter to increase by 2, use countero += 2 instead of countero++.
var counterq = 0;
var limitq = 3;
var countero = 0;
var limito = 5;
function AddContent(divName) {
if (counterq == limitq) {
alert("You have reached the limit of adding " + counterq + " inputs");
} else {
var newdiv = new Array()
newdiv[counterq] = document.createElement('div');
newdiv[counterq].className = 'new-rect';
if (counterq == limito) {
alert("You have reached the limit of adding " + countero + " options");
} else {
newdiv[counterq].innerHTML = "Entry " + (countero + 1) + " <br><input type='text' name='myInputs[" + countero + "]'><br>Entry " + (countero + 2) + " <br><input type='text' name='myInputs[" + countero + "]'><br>";
document.getElementById(divName).appendChild(newdiv[counterq]);
countero += 2;
}
counterq++;
}
}
.new-rect {
width: 300px;
height: 100px;
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="Content"></div>
<input type="button" class="AddContent" value="Add content" onclick="AddContent('Content');">

dynamically removing textbox

I am dynamically adding and removing textboxes though I can successfully adds textbox but unable to remove textbox on clicking the remove button every time i have to reload the browser to remove the textboxes after clicking remove button.
here is my javascript for adding and removing textboxes.
<script type="text/javascript">
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
});
</script>
here is my html for textboxes.
<div id="TextBoxesGroup">
<div class="control-group">
<label class="control-label">answer_1: </label>
<div class="controls">
<input type="text" name="answer_1" id="answer_1" required="true" >
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1">Rank 1</label>
<div class="controls">
<input type="text" name="rank_1" id="rank_1" required="true">
</div>
</div>
<div class="control-group">
<label class="control-label">answer_2: </label>
<div class="controls">
<input type="text" name="answer_2" id="answer_2" required="true" >
<button class="btn btn-mini btn-danger" data-toggle="button" type="button" id="removeButton">
-
</button>
<button class="btn btn-mini btn-success" data-toggle="button" type="button" id="addButton">
+
</button>
</div>
</div>
<div class="control-group">
<label class="control-label" for="rank1" required="true">Rank 2</label>
<div class="controls">
<input type="text" name="rank_2" id="rank_2" required="true">
</div>
</div>
</div>
can anyone what's wrong in it so that I am unable to remove textboxes on clicking the button ? Thanks
you need to modify 2 things here:
1- when appending the new elements, mark their holding div with the current COUNTER value at the end, so it's easy to target them later (like on step 2 below).
so adding new elements should be like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group'+COUNTER+'">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
...
...
instead of this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
2- when removing elements, we will target those with the current COUNTER value at the end of their class name,this way you will remove the last group, and still check if the groups are 3 or lower, no removal should happen.
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$(".control-group"+COUNTER).remove();
});
});
Update: check my updated fiddle http://jsfiddle.net/qqqyC/1/
note: considering that we are appending the COUNTER value at the end of the class name. if class is giving you any styles it will not work. in this case you should not use class name as the target property and consider marking the new group using another attribute/property, and target this attribute/property when removing your elements.
Use .on as you want to bind $("#removeButton").click(function () { to dynamically added elements. It should be
$("#removeButton").on("click", function () {
//.....
});
$(document).ready(function(){
var COUNTER = 3;
var labelArray = ["answer", "rank"];
$("#addButton").click(function () {
for(var i = 0; i < labelArray.length; i++){
createNewInput(labelArray[i]);
}
COUNTER++;
});
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#answer_" +COUNTER).parent('div').parent('div').remove();
$("#rank_" +COUNTER).parent('div').parent('div').remove();
});
});
Please update script or check this fiddle http://jsfiddle.net/Cne2Q/
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#TextBoxesGroup" +COUNTER).remove();
});
What you're doing here, - you're trying to remove an element like $("#TextBoxesGroup1") which obviously doesn't exist. So what you need to do is modify your create new input like this:
function createNewInput(label){
var tbDiv = $('#TextBoxesGroup');
var str = '<div id="textBoxContainer'+COUNTER+'" class="control-group">';
str += '<label class="control-label">' + label + " " + COUNTER + '</label>';
str += '<div class="controls">';
str += '<input type="text" id="' + label + '_' + COUNTER + '" name="'+ label +'_' + COUNTER + '" />';
str += '</div>';
str += '</div>';
tbDiv.append(str);
};
and your remove button
$("#removeButton").click(function () {
if(COUNTER==3){
alert("No more textbox to remove");
return false;
}
COUNTER--;
$("#textBoxContainer" +COUNTER).remove();
});

how to select only one radio button at a time having different name using jquery?

html code:
<div id="localPropList"></div>
<div id="assignedPropList"> </div>
js code:
function getLocalProposals()
{ // filling these radio buttons dynamically
var htmlStringLocalPro = '<fieldset id="local_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var k = 0; k < result.rows.length; k++) {
var localProposal = result.rows.item(k);
if( !(jQuery.inArray( localProposal.id, arrForQueuePropId ) >=0 ) )
{var fieldId = 'localPro' + k;
htmlStringLocalPro += '<input group="1" type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + localProposal.enquiry_no + ',' + localProposal.id + '"/>'
+ '<label for="' + fieldId + '" data-iconpos="right">' + localProposal.enquiry_no+'-'+localProposal.caller_name+'</label>';
}
htmlStringLocalPro += '</fieldset>';
}
function getAssignedproposals()
{
var htmlString = '<fieldset id="assigned_proposal_id_div" name ="radioGroup" data-role="controlgroup">';
for (var i = 0;i < obj.Proposal.length; i++) {
proposalIds += obj.Proposal[i].id + ',';
if( !(jQuery.inArray( obj.Proposal[i].id, arrForQueuePropId ) >=0 ) ){
var fieldId = 'ap' + i;
htmlString += '<input group="1" type="radio" name="assigned_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
// htmlString += '<input type="radio" name="local_proposal_id" id="' + fieldId + '" value="' + obj.Proposal[i].enquiry_no + ',' + obj.Proposal[i].id + '"/><label for="' + fieldId + '" data-iconpos="right">' + obj.Proposal[i].enquiry_no + '-' + obj.Proposal[i].caller_name + '-' + obj.Proposal[i].post_code + '</label>';
}
}
htmlString += '</fieldset>';}
$("input:radio[name=local_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
$("input:radio[name=queue_proposal_id]:checked").each(function () {
var prop = $(this).val().split(',');
});
i need to select only one radio button at a time if radiobutton having name="assigned_proposal_id" is selected then it should not allow to select any radio buttons for name="local_proposal_id]" i cannot assign id different i need to do selection on the basis of name and i cant assign same name to separate group as well
please tell me whats the solution
Checking / Unchecking in jQuery Mobile, you need to use .prop to checked or unchecked and then call .checkboxradio('refresh').
Demo
$(document).on('pageinit', function () {
$(document).on('change', '[type=radio]', function (e) {
// Uncheck radio buttons in #group1 and #group2
$('#group1 [type=radio]:checked, #group2 [type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// "OR" to select all radio buttons in DOM
$('[type=radio]:checked').prop('checked', false).checkboxradio('refresh');
// Check clicked radio
$(this).prop('checked', true).checkboxradio('refresh');
});
});
try the following
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
$('input [name="assigned_proposal_id"]').click(function(){
if($('input [name="assigned_proposal_id"]').is(':checked')){
$('input [name="local_proposal_id"]').attr('disabled' , true)
}
});
It will work like what hussain told
Here A FIDDLE for your purpose. It will uncheck all the radio button, then check the one we clicked on.
HTML :
<div id="localPropList">
<input name="assigned_proposal_id" type="radio" value="value1-1" />value1-1
<input name="assigned_proposal_id" type="radio" value="value1-2" />value1-2
<input name="assigned_proposal_id" type="radio" value="value1-3" />value1-3
</div>
<br/>
<div id="assignedPropList">
<input name="local_proposal_id" type="radio" value="value2-1" />value2-1
<input name="local_proposal_id" type="radio" value="value2-2" />value2-2
<input name="local_proposal_id" type="radio" value="value2-3" />value2-3
</div>
div selected : <span></span>
JQUERY :
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').change(function(){
$('#localPropList input[name="assigned_proposal_id"], #assignedPropList input[name="local_proposal_id"]').prop('checked', false);
$(this).prop('checked', true);
$('span').html($(this).val());
});
Disable Syntax:
$('input[name="name_here"]').attr('disabled', 'disabled');
Don't go for the hardest thing
Hussein Nazzal is correct but space matters
between input and '[' bracket
if($('input[name="assigned_proposal_id"]:checked').val() != '')
{
$('input[name="local_proposal_id"]:radio').attr('disabled', 'disabled');
}
Demo
This worked for me, take into account that according to the selector this change will apply to all RadioButtons in the document with the same class, in this case class="chartIndex":
$(".chartIndex").change(function () {
$('[type=radio]:checked').prop('checked', false);
$(this).prop('checked', 'checked');
});
Hope this helps someone. Regards.

Categories

Resources