Issues with converting label to input field on button click - javascript

I have modified the answer in the post dicussed here.
In my application I have two buttons - edit and save. When clicked on edit, the labels get converted into input fields, where the user can edit the content and save.
Everything is working fine, but the problem is that when the user clicks on the edit button twice, the content in the input fields becomes blank, i.e. the <input> value becomes blank.
Please suggest me a fix for this. Where am I going wrong?
<div id="companyName">
<label class="text-cname"><b>#Html.DisplayFor(m => m.Company)</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" />
</div>
<script>
$(document).ready(function () {
$('#edit').click(function () {
// for company name
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});
</script>

You can use replaceWith() method to convert label to textarea.
$("#edit").click(function(){
var text = $("label").text();
$("label").replaceWith("<input value='"+text+"' />");
});
$("#save").click(function(){
var text = $("input ").val();
$("input ").replaceWith("<label>"+text+"</label>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="edit">Edit</button>
<button id="save">Save</button>
<br/><br/>
<label>Text</label>

The most simple fix would be to disable the edit button once you've clicked it, and enable it again after saving:
$(document).ready(function () {
$('#edit').click(function () {
$(this).prop('disabled', true);
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />')
$('.text-cname').text('').append(lblCName);
lblCName.select();
});
$('#btnSave').click(function () {
$('#edit').prop('disabled', false);
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
});
});

When you click the second time the value of companyName is empty, that's why the <input> value becomes blank. This is a very simple solution, but you lose the focus on edit box which is easy to fix.
$('#edit').click(function () {
/*for company name*/
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if(companyName != "")
$('.text-cname').text('').append(lblCName);
lblCName.select();
});

Try This one
function EditContent(){
var companyName = $('.text-cname').text();
var lblCName = $('<input id="attrCName" type="text" value="' + companyName + '" />');
if (companyName != "") {
$('.text-cname').text('').append(lblCName);
}
lblCName.select();
}
function SaveContent(){
var text = $('#attrCName').val();
$('#attrCName').parent().text(text);
$('#attrCName').remove();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="companyName">
<label class="text-cname"><b>Company</b></label>
</div>
<div class="row center-block">
<input type="submit" class="btn btn-success" value="Save" id="btnSave" onclick="SaveContent()" />
<input type="button" id="edit" class="btn btn-primary" value="Edit" onclick="EditContent()" />
</div>

Related

Add new row with dropdown on button click

I'm trying to add new rows on button click:
<div class="row" style="margin: 20px 0;">
<div id="AddContainer">
<!--new rows with content to add will be added here-->
</div>
<br />
<input id="btnAdd" type="button" class="btn btn-success" value="+" />
</div>
and JavaScript:
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(''));
$("#AddContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
var ddlId = $('[id*=hfDDLId]').val();
$('[id$=ddl' + parseInt(ddlId) + ']').remove();
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
$('[id*=hfdropdownids]').val(resultids);
//}
});
function GetDynamicTextBox(value) {
var combo = $("<select></select>").attr("id", value).attr("name", value).attr("runat", "server").attr("class", "class").attr("required", "required");
$.each(document.pvm.SettingsList(), function (i, el) {
combo.append("<option value=" + el + ">" + el + "</option>");
});
return '<input type="button" value="-" class="remove btn btn-danger" />&nbsp'
+ combo + '&nbsp'
+ '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp'
}
function ClearAddTab() {
document.getElementById("AddContainer").innerHTML = "";
}
and the settings list is:
_mVM.SettingsList = ko.observableArray(['France', 'Germany', 'Spain']);
The problem is that I want need to add the dropdown with the SettingsList options for each new added row, but it displays [object object].
It is possible to add the dropdown between the red button and the text field, but also to allow the user to delete that row by pressing the red button?
In this case you want the HTML of the selected DOM object rather than the object itself.
When running function GetDynamicTextBox try combo.prop('outerHTML') when returning the string and you should get the dropdown html rather than [object object].
JsFiddle: jsfiddle.net/fgazfLaz
HTML
<div class="row" style="margin: 20px 0;">
<div id="AddContainer">
<!--new rows with content to add will be added here-->
</div>
<br />
<input id="btnAdd" type="button" class="btn btn-success" value="+" />
</div>
Javascript
var settingsListAry = ['France', 'Germany', 'Spain'];
$("#btnAdd").bind("click", function () {
//var test = GetDynamicTextBox('a');
//alert("test");
var div = $("<div />");
div.html(GetDynamicTextBox(''));
$("#AddContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
var ddlId = $('[id*=hfDDLId]').val();
$('[id$=ddl' + parseInt(ddlId) + ']').remove();
$('[id*=hfDDLId]').val(parseInt($('[id*=hfDDLId]').val()) - 1);
var previousDropDownId = $('[id*=hfDropDownIds]').val();
$('[id*=hfdropdownids]').val(resultids);
//}
});
function GetDynamicTextBox(value) {
var combo = $("<select></select>").attr("id", value).attr("name", value).attr("runat", "server").attr("class", "class").attr("required", "required");
$.each(settingsListAry, function (i, el) {
combo.append("<option value=" + el + ">" + el + "</option>");
});
return '<input type="button" value="-" class="remove btn btn-danger" />&nbsp'
+ combo.prop('outerHTML') + '&nbsp'
+ '<input name = "DynamicTextBox" type="text" value="' + value + '" required/>&nbsp'
}
function ClearAddTab() {
document.getElementById("AddContainer").innerHTML = "";
}
First add a <div> inside <div id="AddContainer"> this will hold for appending a new input.
<div id="AddContainer">
<!--new rows with content to add will be added here-->
<div></div>
</div>
Add an onclick event on your button then call this function, it will append a new button:
<script>
function addButton()
{
$('#AddContainer')
.find('div')
.remove()
.end()
.append('<input type="button" value="button"
/><div></div>');
}
</script>
Your input button:
<input id="btnAdd" type="button" onclick="addButton();" class="btn btn-success" value="+" />

Dynamically add and remove TextBoxes and get value of dynamic TextBox using jQuery and display it in a textbox

i have code where you can add or delete textbox using .append() and .remove() in jquery, now i want to implode all the value of the textboxes separated by commas and pass it into another textbox located outside the script. how can i do it? here's the code for dymically adding and removing textbox. (not mine just got it here in stackoverflow)
HTML:
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs /jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function () {
var values = "";
$("input[name=DynamicTextBox]").each(function () {
values += $(this).val() + "\n";
});
alert(values);
});
$("body").on("click", ".remove", function () {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
</script>
Use .val() to set value of "another textbox" to values
$(function() {
$("#btnAdd").bind("click", function() {
var div = $("<div />");
div.html(GetDynamicTextBox(""));
$("#TextBoxContainer").append(div);
});
$("#btnGet").bind("click", function() {
var values =
$.map($("input[name=DynamicTextBox]"), function(el) {
return el.value
}).join(",\n");
$("#anotherTextbox").val(values);
});
$("body").on("click", ".remove", function() {
$(this).closest("div").remove();
});
});
function GetDynamicTextBox(value) {
return '<input name = "DynamicTextBox" type="text" value = "' + value + '" /> ' +
'<input type="button" value="Remove" class="remove" />'
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input id="btnAdd" type="button" value="Add" />
<br />
<br />
<div id="TextBoxContainer">
<!--Textboxes will be added here -->
</div>
<br />
<input id="btnGet" type="button" value="Get Values" />
<input id="anotherTextbox" type="text" />

Jquery - dynamically added input field doesn't send value to post

I have this particular jquery code to add/remove fields on a form and then send its values:
$(document).ready(function() {
$("#add").click(function() {
var intId = $("#reglas div").length + 1;
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');
var fName = $('<input align="left" type="text" placeholder="Path" class="reglas_wrapper" id="path" name="field1_' + intId + '" required /> ');
var fName2 = $('<input type="text" class="reglas_wrapper" placeholder="TTL" id="ttl" name="field2_' + intId + '" required />');
var removeButton = $('<input align="right" type="button" id="del" class="remove" value="-" /> <br><br>');
removeButton.click(function() {
$(this).parent().remove();
});
fieldWrapper.append(fName);
fieldWrapper.append(fName2);
fieldWrapper.append(removeButton);
$("#reglas").append(fieldWrapper);
});
$("#cache").each(function() {
$(this).qtip({
content: {
text: $(this).next('.tooltiptext')
}
});
});
});
$('#formsite').on('submit', function (e) {
//prevent the default submithandling
e.preventDefault();
//send the data of 'this' (the matched form) to yourURL
$.post('siteform.php', $(this).serialize());
});
In which you can add/remove fields on the Cache section but the form sends every value except those which were added dynamically.
How can I solve it? You can see the posted form data with Firebug.
Here is a JS Fiddle for you: http://jsfiddle.net/34rYv/121/
Also I realized that when I delete fields, its name doesn't rename.
Maybe you can help me with this too :)
Thanks in advance
Nicolas
Your Cache section stands outside the <form> tags as i see in the source code, so that could be why your fields are not submitted.
Put your form around the left/right div like this:
<div id="wrapper" align="center">
<div class="container" align="center">
<form id="formsite"> // your form starts here
<div id="left">
</div>
<div id="right">
</div>
</form>
</div>
</div>
Instead of this ( what you have right now ):
<div id="wrapper" align="center">
<div class="container" align="center">
<div id="left">
<form id="formsite"> // your form starts here
// the form will automatically be closed in this div
</div>
<div id="right">
</form> // this one will go away
</div>
</div>
</div>
Also, try to keep your code clean, For example:
var fieldWrapper = $('<div></div>',{
class: 'fieldwrapper',
id: 'field'+intId
});
This is way cleaner than:
var fieldWrapper = $('<div class="fieldwrapper" id="field' + intId + '"/>');

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

How Could i rearrange textboxes which are named as array index

i am working on a project in which i have to render rows dynamically . but user could also delete that row have a look at my current working
JQuery
var counter = 1;
function addrow() {
var textbox = "<div id='rows" + counter + "'> </br><label> Option : </label><input type='text' name='Answers[" + counter + "]' class='ahsan required' />Remove</div>";
var form = $("#form").valid();
if (form) {
$("#TextBoxesGroup").append(textbox);
counter++;
}
else {
return false;
}
}
html
<div id="TextBoxesGroup" style="margin-left: 100px;">
<div id="rows0">
</br><label>
Option :
</label>
<input type='text' name='Answers[0]' class='ahsan required' />Remove
</div>
</div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' /></div>
Now , if i have 10 rows there names will be Answers[0,1,2,3,4,5] . I want to remove input when i click on remove anchor and also reoder all textbox's name
For Example if i remove input at 4th index then all textbox automatically get re arranged . Can i Do it Please Help me and Thanks in Advance
You can make it without counter. This way your answers will be always ordered in the array starting by zero.
Here's a plausible solution:
$(function(){
$("#form").validate();
this.addrow = function() {
if ($("#form").valid()) {
var textbox = "<div> </br><label> Option : </label><input type='text' name='Answers["+$("#TextBoxesGroup div").length+"]' class='ahsan required' /><a class='remove-me' href='#'>Remove</a></div>";
$("#TextBoxesGroup").append(textbox);
$('.remove-me').click(function(){
$(this).parent().remove();
return false;
});
}
else {
return false;
}
}
this.addrow();
});
and the html is simple like this:
<form id="form">
<div id="TextBoxesGroup" style="margin-left: 100px;"></div>
<div>
<input type="button" value="Add another row" onclick="addrow();" class="qa-adbtn" id='addButton' />
</div>
</form>

Categories