I have a form where user can submit a few values and they get stored inside a list in a span separated by a comma, like this:
<li>
<span>
Harvard,Marketing,2009,2014
</span>
<br><a>[Remove]</a>
<br><a>[Edit]</a>
</li>
//output
Harvard,Marketing,2009,2014
[Remove]
[Edit]
When clicking on [Edit] I'd like to show up the form replacing the list space with the values in the span filling the inputs showing in the new form so the user can modify them and save again. How can I accomplish this?
Complete code on jsFiddle: http://jsfiddle.net/YueX2/
Please run it so you can see how it works, just click on "Add another" and then on the "Save" button.
is a bit messy but should give you an idea how to do this.
the given template for the "li" is slightly modified
<li>
<span>
Harvard,Marketing,2009,2014
</span>
<br>[Remove]
<br>[Edit]
</li>
the code could be like this:
$('.edit').click(function(){
var parent = $(this).parent();
//get the String from the span element
var values = $.trim( parent.find('span').text() );
//and plit them
values = values.split(',');
//prepend an container to hold the inputs
parent.prepend('<div class="editCont"></div>');
var container = parent.find('.editCont');
//create inputs for each of the seperated values
for(var v in values){
container.append('<input type="text" value="'+values[v]+'" /><br>');
}
//create save link and bind click event to it
container.append('<a href="#" class="editContButton" >save</a><br>');
parent.find('.editContButton').click(function(){
//collect all values from the inputs
var text = [];
var inputs = container.find('input');
for(var i = 0; i < inputs.length; i++){
text.push( $(inputs[i]).val() );
}
parent.find('span').show();
//replace the text in the span element and remove container with inputs again
parent.find('span').text( text.join(",") );
container.remove();
})
parent.find('span').hide();
});
If clicked on Edit the text in the span is split and an input for every entry is created and at the end i add a save link.
If the link is klicked the inputs get joined to an sting and replace the old text in the spawn.
the hide and unhiding of the spawn is optional ;)
When edit is clicked, you can split the content of that span, since it's already comma separated. Then you can take new input and apply it to the span on save. I edited your edit function, and added a new save function.
//existing edit method
$(document).on('click', '.edit', function () {
//hides edit and remove buttons
$(".removeParent, .edit").hide();
//splits span into separate terms
var terms = $(this).siblings("span").html().split(",");
//makes new form
$(this).parents("li").append("<input id='edit1' type='text' value=" + terms[0] + ">" + "<input id='edit2' type='text' value=" + terms[1] + ">" + "<input id='edit3' type='text' value=" + terms[2] + ">" + "<input id='edit4' type='text' value=" + terms[3] + "><input type='button' class='saveEdit' value='Save'>");
});
//additional save method
$(document).on('click', '.saveEdit', function () {
//unhides edit and remove buttons
$(".removeParent, .edit").show();
//makes the new string for the span
var newString = $("#edit1").val()+","+$("#edit2").val()+"," +$("#edit3").val()+","+$("#edit4").val();
//replaces the html of the span with the new string
$(this).siblings("span").html(newString);
//hides new form and save button
$(this).hide();
$("#edit1, #edit2, #edit3, #edit4").hide();
});
Related
Note: Willing to use jQuery, whatever is easier.
I have a form which when submitted, creates a checkbox input. The text of the checkbox should be equal to that of another text input when the form is submitted.
The checkbox is created as expected when I submit the form but it is blank and doesn't contain the text from the corresponding text area.
For a checkbox i'm not sure if I should be using .text, .innerhtml, .val etc and the previous questions I saw on here seemed unnecessarily complicated.
HTML:
<div id="listContainer">
<form id="listForm">
<input type="submit" value="Add">
<input id="listInput" class="textarea" placeholder="Add your list item here, then click submit.">
<div id="checkboxContainer">
</div>
</form>
</div>
JS:
//ADD LIST ITEM
$("#listForm").submit(function(ev) {
ev.preventDefault();
if ($("#listInput").val() == "") {
alert("Please enter the item name, then click 'Add'.");
} else {
listCount++;
var input = $("#listInput").val();
console.log("List Count: " + listCount);
console.log(input);
var cb = document.createElement('input');
cb.id = 'input' + listCount;
cb.type = 'checkbox';
document.getElementById("checkboxContainer").appendChild(cb);
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
//Store the list count
localStorage.setItem("listCount", listCount);
//Store the list title
localStorage.setItem("input" + listCount, input); //"Note " + noteCount + ": " +
this.submit();
}
});
var label = document.createElement('label');
label.id = 'label' + listCount;
$("#label" + listCount).attr("for", "input" + listCount).html(input);
document.getElementById("checkboxContainer").appendChild(label);
These four lines can be cleaned up and fixed. The issue here is quite simple, however your constant back-and-forth between jQuery and plain JS makes things very difficult to read. I would suggest writing DOM manipulation in one or the other, but never both.
The error here is on the third line, which uses the selector $("label" + listCount). This selector will look for this element on the page, however you've only created the element - you haven't added it to the page yet.
Let's correct this and rewrite it in jQuery:
$("<label />") //create new label
.attr("id", "label" + listCount) //set ID
.attr("for", "input" + listCount) //set For
.html(input) //set contents
.appendTo("#checkboxContainer"); //add to checkbox container
Consider using the example above to rewrite your checkbox creation as well, that way you can avoid the mixture of jQuery/plain JS.
In my app I am creating some dynamic textboxes by clicking an add button. We can put some values and time also. Now my need is that when the page loads, I want a given number of textboxes to be created and populated by a set of values. I am able to create the text boxes onload but cannot set the values. Here I am giving a fiddle where I have created my functionality. How can I set some values dynamically? Here is the fiddle MYFIDDLE
And also I want timepicker function in those onload created boxes.
function getTextBoxAfterValiddation(val){
var str_array = ['jeet','chatterjee'];
var randomId = '\''+"#interviewName"+val+'\'';
var nameId = "interviewName"+val+"";
var allNames = str_array.replace(/((\[)|(\]))/g,"");
alert(randomId)
$(randomId).val(arr[val]);
return '<input class="txt1" name = "DynamicTextBox" type="text" id = "'+nameId+'"/>';
}
for(var i = 0; i < 4; i++){
var div = $("<div />");
div.html(getTextBoxAfterValiddation(i));
$("#TextBoxContainer").append(div);
}
When you dynamically generate each element increment a counter and use that value as the elements id. Then you can put html or values into each element using jquery. In the example below every time i click a button with id "addphys" i append a new div on. Later i can grab values from each div because i know the count and each new div id is phys1, phys2, phys3...
var numphys = 0;
$("#addphys").click(function(){
$("#test").append("<div class=\"addedphys\"><p id=\"phys"+ numphys + "\"><p><label>Physician Username:</label><input type=\"text\" class=\"inputbox\" id=\"physusername" + numphys + "\" name=\"pass\"></p><p><label>Physician Password:</label><input type=\"text\" class=\"inputbox\" id=\"physpassword" + numphys + "\" name=\"pass\"></p></p></div>");
numphys += 1;
});
Hope that helps.
I have an indeterminate number of span and input tags with random IDs.
The user has the ability to change the HTML inside of <span> but not <input>.
It looks like this:
<span id="0">235</span>
<input id="5239aac3" value=235>
<span id="1">12</span>
<input id="123abc2" value=12>
<span id="2">235</span>
<input id="5res345" value=235>
I have put all the IDs of <input> into an array called arrayOfIDs and through JavaScript given all matching <span> tags and Id of the index.
for (var i = 0, l = arrayOfIDs.length; i < l; ++i) {
$('#' + i).on("change", function(){
var txt = $(this).find().text();
var $idval = $(arrayOfIDs[i]);
$idval.val(txt)
}).trigger("change");
}
What I need help with in the code above is how to monitor the change in the innerHTML of all spans and update the corresponding input.
I think that you need to change your first selector from $('#i') to $('#' + i)
otherwise you're selecting the element with the literal id of 'i' , which doesn't exist
Also, is the function firing at all? If so, what output do you get?
Finally, I think that you'll want to change var $idval = $(arrayOfIDs[i]); to var $idval = $('#' + arrayOfIDs[i]);
I have a grid (dhtmlx) with lots of rows. What I am trying to achieve is to get all the values of clicked radio button of each row plus the row id separated by comma and put it into an input box ? The row ids and radio button values are separated by :
The row ids are automatically generated in this format 110014742~01~01
rowId:radioBtnValue, rowId:radioBtnValue, rowId:radioBtnValue
13004238~01~01:02, 110012178~01~01:05, 110014742~01~01:03 --> inside the input box when the radio buttons are clicked.
The column that contains all the radio button and its header had an id of rbBtn_sel
There will be another button when it is clicked will take the values from the input box and save it.
function DoRowSaveConfig() {
var colIndex=mygrid.getColIndexById("rdBtn_sel");
var radioBtn = mygrid.getCheckedRows(colIndex);
var CommaCount = radioBtn.split(",").length - 1 ;
for (var i= 0; i<radioBtn.length; i++)
if (radioBtn[i].checked) {
var selectedVal = radioBtn[i].value;
document.getElementById('an.ret.sys.4.').value = selectedVal;
document.getElementById('an.ret.sys.5.').click();
}
}
return false;
};
Maybe Jquery will have a better solution. Open to it.
http://jsfiddle.net/19eggs/ep6JE/
/**********EDIT**************/
Thanks all, and it works as expected but I may have mislead you. Upon clicking the radio button it needs to get the value of the row id not id(second col). Updated the image.
Row ids are automatically generated in this format 110012178~01~01. Also we are using xml and DHTMLX grid will automatically convert to a table.
<rows><row id="13004238~01~01"><cell>James Brown</cell>
<cell>12545</cell>
<cell><![CDATA[<div class="rd"><input type="radio" name="130042380101" value="00"></div>
<div class="rd"><input type="radio" name="1100121780101" value="01"></div>
<div class="rd"><input type="radio" name="130042380101" value="02"></div>
<div class="rd"><input type="radio" name="130042380101" value="03"></div>
<div class="rd"><input type="radio" name="130042380101" value="04"></div>
<div class="rd"><input type="radio" name="130042380101" value="05"></div>
<div class="rd"><input type="radio" name="130042380101" value="06"></div>]]>
</cell>
</row>\</rows>';
Here is my attempt - note it is much simpler than the map and assume you only have radios that you want to handle on the page
Live Demo
$(function() {
$("input[type=radio]").on("click",function() {
var clicked = [];
$("input[type=radio]:checked").each(function() {
clicked.push($(this).closest("td").prev().text()+"~"+this.value);
});
$("#an\\.ret\\.sys\\.4\\.").val(clicked);
});
});
If you need the NAME of the radio:
clicked.push(this.name+":"+this.value);
Use .map()
Fiddle Demo
function DoRowSaveConfig() {
var arr = $('table').find('input[type="radio"]:checked').map(function () {
return $(this).closest('tr').find('td:eq(1)').text() + ':' + this.value;
}).get().join();
console.log(arr);
};
Using .map() which create an array with .join() allow you to do that :
function DoRowSaveConfig(){
var arr = $('tr:not(:first)').map(function(){
var id = $.trim($(this).find('td').eq(1).text()); //1 == second column
var value = $(this).find(':checked').val(); //Find the checked one
return id + ':' + value; //Build an array of strings
}).get()
alert(arr.join(', ')); //Join them.
}
http://jsfiddle.net/ep6JE/1/
Edit
After your edit, this code should work :
function DoRowSaveConfig(){
var arr = $('row').map(function(){
var id = this.id;
var value = $(this).find(':checked').val(); //Find the checked one
return id + ':' + value; //Build an array of strings
}).get()
alert(arr.join(', ')); //Join them.
}
I'm using JavaScript to dynamically add rows to a table, I create some textboxes in each row, I've added an onkeyup event to one of my textboxes:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
spanCount.onkeyup = function ()
{
alert(spanTotal.innerHTML);
};
then I add this span (which is rendered as an HTML textbox) to my table row. I want to have value of my dynamically created textbox, but whenever I change this textbox, initial value of this textbox is displayed in alert box (i.e. 1). Initial value of this textbox is "1", but when I change it (for instance type a 0 in textbox), again "1" is displyaed in alert box. I want to have value of my dynamically created textbox, should I give an ID to my span? how should I define spanCount.onkeyup function? where should it be defined so that I can have exact value of this textbox?
I created a jsFiddle. You can get value of input box using childNodes. There are other problems in code you were using spanCount istead of spanTotal.
Modified code:
var myTotal = "1";
var spanTotal = document.createElement("span");
spanTotal.innerHTML = "<input style=\"width:50px\" type=\"text\" name=\"total\" value=" + myTotal + ">";
document.body.appendChild(spanTotal);
spanTotal.onkeyup = function() {
alert(spanTotal.childNodes[0].value);
};
Below modified code maybe can solve your problem:
var myTotal = 1;
/* object creation */
var span = document.createElement('span');
var input = document.createElement('input');
input.setAttribute('type', 'text');
input.setAttribute('name', 'total');
input.setAttribute('style', 'width:50px;');
input.setAttribute('value', myTotal);
// append each object to respective container
span.appendChild(input);
document.appendChild(span);
/* event handler */
input.onkeyup = function(){
alert(this.value);
}