How to append text in a form using ajax/javascript? - javascript

I have a form. Let's called it myform.
Inside there are checkboxes, such as these two:
<input type='checkbox' name='power_convention[]' value='SOME VALUE #1' />
<input type='checkbox' name='power_evidence[]' value='SOME VALUE #2' />
At the end of the form, there's a textarea.
<textarea id="elm1" name="comments" rows="15" cols="80" style="width: 80%">
If power_convention is checked, I want it to immediately append the value of that checkbox into the comments checkbox with the following structure:
<h3>SOME VALUE #1</h3><br />
Similarly, if power_evidence is clicked, I want it to do the same thing, but obviously after whatever came before it.
How would I go about doing this?
Thanks!

A jQuery solution:
$('input[type="checkbox"]').change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val(function(i, v) {
return v.replace(new RegExp(val), '');
});
}
});
DEMO
This only works if val does not contain any special regular expressions characters. In this case you would have to escape them.
Update: Actually, you don't need a regular expression here, v.replace(val, '') will be just fine (thanks #Pinkie);
An alternative to regular expressions would be to recreate the content of the textarea:
var $inputs = $('input[type="checkbox"]');
$inputs.change(function() {
var val = "<h3>" + this.value + "</h3><br />";
if(this.checked) {
$('#elm1').val(function(i, v) {
return v + val;
});
}
else {
$('#elm1').val('');
$inputs.not(this).change();
}
});
DEMO 2

jQuery
$('input[name="power_convention[]"]').click(function() {
// assuming you only want the value if the checkbox is being ticked
// not when it's being unticked
if ($(this).is(":checked")) {
$('#elm1').val("<h3>" + this.value + "</h3><br />");
}
});
If you want them both to insert into the same textarea (and they're the only fields on the page that begin with power_) then you can change the selector to use
jQuery's Attribute Starts With selector:
`$('input[name^="power_"]`
Demo on jsfiddle.

First, you will need to add an onClick event handler to your checkbox:
<input type='checkbox' onClick="someFunction(this)" name='power_convention[]' value='SOME VALUE #1' />
Then, up in the head section, in a script tag, put
someFunction(checkbox) {
document.getElementById("elm1").value += "<h3>" + checkbox.value + "</h3>";
}

Here's a jsfiddle
$('input:checkbox[name*=power_]').click(function(){
value = '<h3>' + $(this).val() + '</h3> <br />';
prevVal = $('#elm1').val();
$('#elm1').val(prevVal + value );
});

Related

how to live populate div using dynamically generated html input types

i'm trying to populate div with select option but i don't really now where to start...
i have some code to live edit the "title" of the div, but now i want to add to a specific div his option...
Here's the code that i have for now:
var rooms = $("#howmanyrooms").val();
var roomcounter = 1;
$(".design-your-system-page-playground-container").show();
for (var i = 0; i < rooms; i++) {
// $("<div class='appendeddiv'>Room-" + roomcounter++ + "</div>").appendTo(".housecontainer");
// $("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id'></div></br>").appendTo(".infoncontainer");
//
$("<div class='design-your-system-page-rooms targetDiv_" + roomcounter + "'>Room-" + roomcounter + "</div>").appendTo(".design-your-system-page-house");
$("<span>Room-" + roomcounter + " name</span> <input type='text' placeholder='name' id='room-" + roomcounter + "-id' class='textInput' lang='targetText_" + roomcounter + "'>&nbsp<select>Heating<option value='radiator'>Radiator</option><option value='underfloor'>Underfloor</option><option value='electric'>Electric</option></select> <select class='design-your-system-number-of-radiator-select'><option value='0'>0</option><option value='1'>1</option><option value='2'>2</option><option value='3'>3</option><option value='4'>4</option><option value='5'>5</option><option value='6'>6</option><option value='7'>7</option><option value='8'>8</option><option value='9'>9</option></select> <span>Do you want the room to be smart (footprint) ?<input type='radio' name='smart-yes' value='smart-yes'>Yes</input> <input type='radio' name='smart-no' value='smart-no'>No</input></div></br>").appendTo(".design-your-system-page-edit-room-container");
roomcounter++;
};
if ($('.design-your-system-page-house').find('.design-your-system-page-rooms').length) {
$("#buttonaddrooms").hide();
}
$("input.textInput").on("keyup", function () {
var target = $(this).attr("lang").replace("Text", "Div");
$("." + target).text($(this).val());
});
as you can see, when i click the button, i'll append to the parent as many child divs as the value typed into the textbox and i also create the same number of "row" containing the name and other option (two select and a radio)
i'm already able to live edit the name of the ralative div, but now i want to add to that div also the other options
here a jsfiddle to help you understand what i have and what i want:
http://jsfiddle.net/3cyST/
if is not clear please tell me.
thanks
please check this fiddle:
i made your target variable global to be reusable, i also added a class for your first select element which is selecting
ive updated it and it now appends the value of your test onchange using:
$("select.selecting").on("change", function () {
$("." + target).append($(this).val());
});
you can work for the rest now.
EDIT(for the question of OP on the comment) :
to get value of radio button i'll give you 2 ways :
in Javascript :
if (document.getElementById('ID_OF_RADIO').checked) {
rate_value = document.getElementById('ID_OF_RADIO').value;
}
in jQuery :
$("input[name=RADIO_NAME]:checked").val();
give the select an id, then use
$("#id").on("change",function(){
console.log(this.value);
//whatever you want to do with the value
})
...same for the radio buttons and other options...also note that the radio buttons shouldn't have different names:
<input type='radio' name='radio_{put id here}' value='yes'>Yes</input>
<input type='radio' name='radio_{put id here}' value='no'>No</input>
another thing for the readabillity of the code: try using a template....just put a <noscript> with an id in the code...use some distinctive syntax to put placeholders in it, and replace them at runtime:
HTML:
<noscript id="template">
RoomName: <input type="text" id="roomName_%ROOMID%" />
Do you want...
<input type='radio' name='radio_%ROOMID%' value='yes'>Yes</input>
<input type='radio' name='radio_%ROOMID%' value='no'>No</input>
</noscript>
JS:
for (var i = 0; i < rooms; i++) {
var tplcode = $("#template").html();
tplcode = tplcode.replaceAll("%ROOMID%",roomcounter);
$($.pareHTML(tplcode)).appendTo(".design-your-system-page-edit-room-container");
$("input[name='radio_"+roomcounter+"']").on("change",function(){
console.log("user wants:" + $("input[name='radio_"+roomcounter+"'][checked]").val())
});
roomcounter++;
}
// these functions help replacing multiple occurances
String.prototype.replaceAll = function(find,replace){
return this.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
//escapse all regEx chars, so the string may be used in a regEx
function escapeRegExp(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
}
Fiddle: http://jsfiddle.net/3cyST/4/

Text of the HTML checkbox

HTML
<input type="checkbox" value="One" checked="checked" id="r1" name="g" />
<label for="r1">
One
</label>
<input type="checkbox" value="Two" id="r2" name="g" />
<label for="r2">
Two
</label>
<input type="button" value="Status" onclick="MyFunction()" />
Javascript
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked == true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextSibling.innerHTML);
}
}
}
Here I am getting the Index of the checkboxes which are checked.
How to get the text of the selected Checkboxes?
Demo:http://jsfiddle.net/u95uN/
Thanks for ur help.
Because in many browsers, the nextSibling will be an empty text node.
USE nextElementSibling instead of nextSibling
WORKING DEMO
The ChildNode.nextElementSibling read-only property returns the
element immediately following the specified one in its parent's
children list, or null if the specified element is the last one in the
list.
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked === true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextElementSibling.innerHTML);
}
}
}
MyFunction();
Since you tagged this with jQuery I'll answer using jQuery.
Here's the fiddle: http://jsfiddle.net/5xL56/3/
Explanation:
On button click:
$("#btn").click
It will run through every checkbox with the name "g":
$("input[type=checkbox][name=g]").each
Try this, You are writing JavaScript on load, mention in head or body as below:
function MyFunction() {
var chk = document.getElementsByName("g");
for (var i = 0; i < chk.length; i++) {
if (chk[i].checked === true) {
alert("Checkbox at index " + i + " is checked!");
alert("Text at index " + i + chk[i].nextElementSibling.innerText);
}
}
}
Demo
Use chk[i].value to fetch the value of the checked checkbox.
alert("Text at index " + i + chk[i].value);
Demo
Please correct this line !
alert("Text at index " + i + chk[i].nextSibling.nextSibling.innerText);
Or you can use;
alert("Text at index " + i + chk[i].nextElementSibling.innerText);
Or you can use; (My way)
alert("Text at index " + i + chk[i].value);
To see this options, you can write in javascript your code "console.log(chk[i])" than you can see your options to get the text.
Try this I think this would work :
$.each($("input[name='g']:checked"),function(i,element){
var id = $(element).attr("id");
var text = $("label[for='"+id+"']").text();
alert(text);
});
Use nextElementSibling instead of nextSibling
Fiddle demo
nextSibling checks for whatever there is following the current element and hence even line-break or space etc are also considered even if these are not HTML elements and nextSibling() is only for that.
But nextElementSibling searches for the next HTML element that here is the <label> and hence it is what you need.

jQuery input forms issue

I'm currently working on some input forms in JavaScript, and I've edited by script so that once the user enters the number of forces for a problem, new input text fields show up per number, also there is a button which is added at the end of that. The issue is when I try and click this button, I try and use the .map function to start all text field values into it and nothing is happening.
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
function forceRecording(numofforces,$this){
var addRows='<tr id=newRows>';
for(var i =1; i<=numofforces;i++)
{
var nearTr=$this.closest('tr');
addRows=addRows + "<td>Force " +i+": </td><td><form><input type='text' name='forceItem' id='newR'/></form></td>";
}
addRows=addRows+"<td><div class='button' id='forceButton'> Add! </div></td></tr>";
nearTr.after(addRows);
};
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val()
});
prompt("forces");
});
As you can see my forceRecording function is working and creates a new row with new text input fields per the numofforces but once I try clicking the forceButton to enter the values into my forces array nothing happens. Any idea what could be causing this?
You are missing the closing paranthesis around your code here
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){return $(this).val()
});
It should be like this
$('#forceButton').click(function(){
forces=$("input[id='newR']").map(function(){
return $(this).val();
});
});
And don't use the id instead use a class name
$('#forceButton').click(function(){
forces=$(".newR").map(function(){
return $(this).val();
});
});
Apply the class to input field like this
<input type="text" name="forceItem" class="newR"/>
I have absolutely no idea what you're trying to achieve, but maybe this will help:
function forceRecording(numofforces, $this) {
var addRows = '<tr id="newRows">';
for (var i = 1; i <= numofforces; i++)
addRows += '<td>Force ' + i + ': </td><td><input type="text" name="forceItem" /></td>';
addRows += '<td><input type="button" class="button" id="forceButton" value="Add!" /></td></tr>';
$this.closest('tr').after(addRows);
}
$('#forceButton').click(function() {
forces = $(this).parent().parent().filter('input[name="forceItem"]').map(function() { return $(this).val(); });
});

JQuery Add Value of 2 input boxes to a third

I have 3 input boxes in my page.
What I need to do is Onchange add the values of Input box A and Input Box B with a comma separating the two values.
For example:
Input A = 'MyValueA'
Input B = 'MyValueB'
Result = 'MyValueA , MyValueB'
$('#inputa, #inputb').change(function (e) {
var result = $('#inputa').val() + ", " + $('#inputb').val();
$('#inputc').val(result);
});
$("#input1, #input2").bind('change', function(){
$("#input3").val($("#input1").val() + ',' + $("#input2").val());
});
This will allow infinite textboxes
HTML
<input class="valuegroup" id="inputa" />
<input class="valuegroup" id="inputb" />
<input class="output" id="inputz" />
JS
$(function() {
$('.valuegroup').on('change keyup', function() {
var myVal, newVal = $.makeArray($('.valuegroup').map(function(){
if (myVal = $(this).val()) {
return(myVal);
}
})).join(', ');
$('.output').val(newVal);
});
});​
DEMO

Element is not defined jQuery $(element).remove()

I have this JavaScript that adds a form field, along with a link to remove that field:
var fieldCount = 0;
function addField() {
var name = 'file' + fieldCount;
var row = 'row' + fieldCount;
var str = '<p id="' + row + '"><label for="' + name + '">File to upload: <input type="file" name="' + name + '" id="' + name + '" />(100MB max size) <a onclick="removeRow(' + row + '); return false;">[-]</a></label></p>';
fieldCount++;
$("#fields").append(str);
};
function removeRow(id) {
$(id).remove();
};
Here is the markup:
<form id="ajaxUploadForm" action="<%= Url.Action("AjaxUpload", "Upload")%>" method="post" enctype="multipart/form-data">
<fieldset id="uploadFields">
<legend>Upload a file</legend>
<div id="fields"></div>
<input id="ajaxUploadButton" type="submit" value="Submit" />
</fieldset>
<a onclick="addField(); return false;" id="add">Add</a>
<div id="resultBox">
<p id="status" style="margin:10px;"></p>
</div>
</form>
The addFields works as expected, but when I click the remove link firebug tells me that row# is not defined, where # is any number of the added fields.
Any help would be appreciated!
You need to pass a valid selector expression for an ID selector (#ID), either in the removeRow call (also note the quotes surrounding the ID selector):
'<a onclick="removeRow(\'#' + row + '\'); return false;">'
Or in the removeRow function itself:
function removeRow(id) {
$("#" + id).remove();
};
You need to have quotes around it, since it's a string.
You also need the "#" to make it into a selector:
var str = '... <a onclick="removeRow(\'#' + row + '\'); return false;">...';
A better way would be to assign the onclick as a function (not sure of the jQuery way to do this but in plain Javascript):
var a = document.createElement('a');
a.onclick = (function(row)
{
return function()
{
removeRow(row);
return false;
};
})();
You are passing in the string value of row12, but the selector should be:
$('#'+row).remove()
The # specifies that you are looking for an ID. I agree with what I think one of the other answers was about to say, you should just use the onclick events natural this keyword instead:
<p onclick="remove(this)">something</p>
function remove(what) {
$(what).remove()
}
Or, maybe just forget the whole thing all together and switch to behavior for those kinds of rows:
$('.removableRow').live('click', function() {$(this).remove()});
Then you just specify that the row is removable, and never have to worry about binding events at all:
<p><a class="removableRow" href="#">Remove</a></p>

Categories