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>
Related
I'm Having a bit of an issue. I'm using JavaScript to inset HTML into a webpage along with an event handler for the onblur event. It looks like this:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(document.getElementById("txIn").value(), 2, 3);" />';
I'm getting a syntax error. However, the following works perfectly fine:
return '<input id = "txtIn" type="text" value=" ' + dateTime + '" onblur= "submitManualDate(1, 2, 3);" />';
Any idea what I'm missing?
Using " inside "(double quoted) expression will break the string.
It's better to pass this as an argument as you should not have multiple elements with same id attributes in a document.
Try this example:
(function() {
var input = '<input type="text" value="5" onblur= "submitManualDate(this, 2, 3);" />';
document.getElementById('parent').innerHTML = input;
})();
function submitManualDate(elem, j, k) {
alert(elem.value + ' ' + j + ' ' + k);
}
<div id='parent'></div>
Fiddle here
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 + "'> <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/
i am creating a dynamic button in javascript and calling a function on its click,but I am not able to pass string parameter to it,what shoud be the proper code.
I am doing this.
document.getElementById(divfield).innerHTML +="<input type='button' value='-'class='remove_this"+i+"' onclick=' removed("+i+",'"+s+"') '>";
here i is a integer,and s is a variable holding string.how should i pass string variable.
I guess you want something like this:
var div = document.getElementById('divfield');
var input = document.createElement('input');
input.type = 'button';
input.value = '-';
input.setAttribute('class', 'remove_this' + i);
input.onclick = function () {
removed(i,s)
}
div.appendChild(input);
jsfiddle: demo
you have missed some quotation mark on your code, if you try this:
innerHTML +="<input ..... onclick=' removed(" + i + ",\" " + s + "\ ") '>";
there will not any problem...
by your code, input element will be created like this: (notice to onclick attribute):
<input type="button" value="-" class="remove_this1" onclick=" removed(1," ss') '>
if: (i = 1) and (s = "ss") for example
By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.
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 );
});