How to dynamically remove input field which is created dynamically using JavaScript - javascript

I created an input text dynamically using JS, but what if I want to remove the input field one by one dynamically using a button by calling "removeTextField()" from the JS?
Here is the JS:
<script type="text/javascript">
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
}
</script>
...
<input type = "button" class="button2" value = "Add Time" onclick = "addTextField()"/>

The way you create the elements has a problem. You are giving the new element a hardcoded id and this means that when adding more than one, you will end with multiple elements with the same id ?(which is invalid and prone to errors when accessing the DOM)
Since you use jQuery, why not simplify your code when adding/removing elements by utilizing it?
I would use something like this
html
<input type="button" class="button2 addField" value="Add Time" />
<input type="button" class="button2 removeField" value="Remove Time" />
script
$(function(){
$('.addField').on('click', function(){
$('<input type="text">', {
name: 'i[]',
value: '',
'class': 'daters'
}).appendTo('#dispTime');
});
$('.removeField').on('click', function(){
$('#dispTime .daters').last().remove();
});
});
If you are not using jQuery then the way to remove an element
function removeTextField(){
var elements = document.getElementById('dispTime').getElementByClassName('i[]'),
last = elements[elements.length-1];
last.parentNode.removeChild(last);
}

function removeTextField() {
var timepicker = document.getElementByID("timepicker_7");
timepicker.parentElement.removeChild(timepicker);
}

you can use $.remove() for this..
refer: http://api.jquery.com/remove/
Suggestion: instead of creating elements like the one you did, create like this.
$('body').append("<input name='i[]' value='' class='daters' id='timepicker_7' />");
$('#timepicker_7').remove();
if you are creating elements on demand and want to use this element multiple times.
now you have a function which can be used as many times you want, anywhere on the page
function GetTextField() {
var field = "<input name='i[]' value='' class='daters' id='timepicker_7' />";
return field;
}
var field = GetTextField();
$('body').append(field);

$("#dispTime #timepicker_7").remove()

This is my idea(not tested):
Every time you add an input, just push it in a array, so you can remove it after:
<script type="text/javascript">
var inputStack = new Array();
function addTextField(){
var element = document.createElement("input");
element.setAttribute("name", "i[]");
element.setAttribute("value", "");
element.setAttribute("class", "daters");
element.setAttribute("id", "timepicker_7");
var myvalue = document.getElementById("dispTime");
myvalue.appendChild(element);
inputStack.push(element);
}
// Now if you want to remove, just do this
inputStack[0].remove(); // I think it'll work for example
</script>

Related

Want to call a javascript function with 2 parameters in innerhtml

I have a JSP containing JavaScript function.Within that I created an inner html code.That contain a button with onClick function.When clicking the button I want to pass 2 parameters to the the function of JavaScript. But I can't get the 2 values properly.Please help me
Thank you
<script type="text/javascript">
function find(){
var i=0;
var servicetypevalue="SERVICE";
var td7= document.createElement("td");
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
}
function getStatus(i,servicetypevalue){
alert("enter");
}
</script>
I want to show the enter alert.But the parameter values are not properly passed.
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus(' + i + ',' + servicetypevalue + ');">';
use string concatenation as given above.
If your'e going to generate your own elements in JS, it's different than jQuery. While in jQuery you can make strings into valid markup reliably, but JS is not as sophisticated. Yes you can make an element by innerHTML, but it's error prone. The procedure to accomplish what you want in plain JS is as follows:
#1. Create an element.
#2. Append element to a parent.
#3. Add attributes to element.
The way your code is, it wouldn't work because your'e skipping #2. .td7 is never appended on the DOM and if the innerHTML of .td7 was rendered, it might succeed that'd be wierd. Instead of using an inline event which limits you, addEventListener gives you much better control and is more manageable. Also your getStatus just alerts "enter" which doesn't prove that your 2 parameters actually were passed. I added another alert as proof that the parameters were passed.
var i = 0;
var servicetypevalue = "SERVICE";
var host = document.querySelector('body');
var td7 = document.createElement('td'); //#1
var ptBtn = document.createElement("button"); //#1
host.appendChild(td7); //#2
td7.appendChild(ptBtn); //#2
ptBtn.className = "button"; //#3
ptBtn.name = "ptBtn"; //#3
ptBtn.id = "ptBtn"; //#3
ptBtn.innerHTML = "View Status"; //#3
function getStatus(i, servicetypevalue) {
alert("enter");
alert("i: " + i + "\nservicetypevalue: " + servicetypevalue)
}
ptBtn.addEventListener('click', function(event) {
getStatus(i, servicetypevalue);
}, false);
window.load = find;
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Try to replace
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="getStatus('i,servicetypevalue');">';
to
td7.innerHTML='<input type="button" value="View Status" class=button name="ptBtn" id="ptBtn" onClick="' + "getStatus('i','servicetypevalue'" + ');">';

How to set what user types in textarea as a javascript variable?

Hi so I have a HTML textarea. I want what the user types in it to be displayed on the screen and also stored in a variable. I have the displaying part but I can't figure out how to store it as a a variable.
The html
<textarea id="input" maxlength="50" name="Text" placeholder="Max. 50 characters"></textarea>
The javascript
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = this.val();
});
Firstly, you should use change or input instead of keyup. Not everyone uses a keyboard!
Second, only jQuery objects have a val() method. Using this you are referring to the <textarea> element which does not:
$('#input').on("input", function() {
var yourText = $(this).val(); // Only jQuery objects have a .val()
$('#text').html(yourText); // Pass your variable in here
});
jsFiddle Demo
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = this.val();
});
Should be
$('#input').keyup(function() {
$('#input').html($(this).val());
var yourText = $(this).val();
});
You gave #text as an id, but the id name of the input is #input
You forget the javascript closure $ on this. Use the code below
<textarea id="input" maxlength="50" name="Text" placeholder="Max. 50 characters"></textarea>
<div id="text1"></div>
<script>
$('#input').keyup(function() {
$('#text').html($(this).val());
var yourText = $(this).val();
$("#text1").html(yourText);
});
</script>
JSFIDDLE:http://jsfiddle.net/7tfs93o2/
Hope this helps you
You are doing var yourText = this.val(); but since you are using JQuery there, .val() is a JQuery method, this should also be wrapped with the JQuery layer like this:
var yourText = $(this).val();

Show submit when checkbox is checked loop

I've got a page in wordpress that displays around 20 poll questions (using WP-polls).
I'm using a snippet to display the submit button for each poll once an answer has been checked. Thing is, with this snippet I have to copy paste it about 20 times, because of that I some kind of loop.
This is the current code I'm using
$(document).ready(function() {
var $submit = $("#btn-7").hide(),
$cbs = $('input[name="poll_7"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-6").hide(),
$cbs = $('input[name="poll_6"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
$(document).ready(function() {
var $submit = $("#btn-5").hide(),
$cbs = $('input[name="poll_5"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
});
As you can see what changes is the "btn_number" ID and "poll_number". This goes on for another 20 snippets. How can I make this dynamic?
jQuery allows you to use wildcards, for example:
var $submit = $("#btn-*").hide(),
$cbs = $('input[name="poll_*"]').click(function() {
$submit.toggle( $cbs.is(":checked") );
});
Edit: I see the wildcard selectors isn't supported by jquery anymore (as above example) you might want to look at: http://james.padolsey.com/javascript/regex-selector-for-jquery/ which gives you the ability to use regex to define the selectors for all btn's and code for it once
You can use the starts with selector on the ID and name attributes, to dynamically access the number. The change event is more appropriate than the click event for checkboxes.
Demo
$('[id^="btn-"]').hide();
$('input[name^="poll_"]').change(function(){
var number = this.name.replace('poll_', '');
$('#btn-' + number).toggle( $(this).is(":checked") );
});
It would be better to use data-* attributes to link the buttons and checkboxes, or nest them in an element that has the ID. Parsing the number out of the ID attribute isn't the cleanest way.
You don't have to repeat the same code for 20 times just for getting different button ids. you can make it dynamic. checkout this simple example
$("#submit").click(
function()
{
for(i=1;i<=5;i++)
{
msg = $("#btn-"+i).val()
alert(msg)
}
}
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="button" id="btn-1" value="button1">
<input type="button" id="btn-2" value="button2">
<input type="button" id="btn-3" value="button3">
<input type="button" id="btn-4" value="button4">
<input type="button" id="btn-5" value="button5">
<p>
<input type="button" value="submit" id="submit">
$(document).ready(function(){
for(var i=1;i<=20;i++){
var submit = $("#btn-"+i).hide(),
cbs = $('input[name="poll_'+i+'"]').click(function(){
submit.toggle($this.is(":checked"));
});
}
});

Creating a Pass Fail Input Function

I am creating a test form. I have created a form with a list of steps to test.
Instead of every item on the list needing:
<input type="radio" name="step1">Pass<input type="radio" name="step1">Fail
I wanted to create a function so I could just call it every time to create it.
This is my function so far:
function createPassFail(name)
{
var Pass = document.createElement('input');
Pass.type = "radio";
Pass.name = name;
document.getElementById("Pass").innerHTML = "Pass";
var Fail = document.createElement('input');
Fail.type = "radio";
Fail.name = name;
document.getElementById("Fail").innerHTML = "Fail";
}
And then I call it with:
<li>Step One: Turn the TV On
<input id = "step1" onload="createPassFail(this.value)">
</li>
All this does is create a textbox which is not what I was going for. I am also not sure if onload is correct.
Instead of passing in the value to the function you should pass the id:
onload="createPassFail(this.id)"
// ^^
I say your event should be onblur because I don't think onload is the event handler you should be using. You can use my suggestion or maybe set up a button next to the text box which, when clicked (using onclick) does what you want.
Moreover, you haven't inserted the pass or fail elements into HTML. Try this:
document.body.appendChild(Pass);
document.body.appendChild(Fail);
This inserts the newly-created elements directly to the end of the body element. If you would like them to be child to some element therein, you would have to access the element with a suitable method. For example, with getElementById:
document.getElementById( element ).appendChild(Pass); // do the same for Fail
However, this can all be easily done with jQuery.
$(document).ready(function() {
function createPassFail(name)
{
$('body').append('<input type="radio" id="' + name + '">Pass');
$('body').append('<input type="radio" id="' + name + '">Fail');
}
$('#step1').ready(function() {
createPassFail(this.id);
});
});
Live Demo

JQuery: Selecting elements with unique class AND id

I have this html code:
<div class="category" id="154"> Category </div>
<div class="category2" id="156"> Category2 </div>
<div class="category3" id="157"> Category3 </div>
<div class="category4" id="158"> Category4 </div>
<input type="text" />
So in example if I write a id in text box, how to select div .category with this ID and get inner HTML text. With jQuery
so you only need to use the ID as this is a unique value (or should be)
var html = $("#154").html();
NOTE: If you do have duplicate ID values in use then it is important to note that JQuery will only select the first one.
if you want to do this when a textbox value is entered you could do this on the textbox change event...
$("input").change(function(){
var id = $(this).val();
var element = $("#" + id);
if(element){
var html = element.html();
//do something with html here
}
});
NOTE: you may want to put an ID value on your textbox to ensure you get the correct control
Although I strongly suggest you find a way around using duplicate ID values, you could have a function like this to get the DIV you want...
function GetContent(className, id) {
var result = null;
var matchingDivs = $("." + className);
matchingDivs.each(function(index) {
var div = $(matchingDivs[index]);
if (div.attr("id") == id) {
result = div.html();
}
});
return result;
}
Click here for working example
I recommend you give the textbox an ID, in case you add other textboxes to the page.
But if you only have the 1 text input, the following would work:
var id = $('input:text:first').val();
var innerHtml = $('#' + id).html();
Here is a jsFiddle that will alert the html using this technique whenever the text in the textbox changes.
$("#id.class")
will select the necessary element by both class and ID (replacing id and class with their respective names, of course).
Adding .html() to the end will get you the content.
i.e:
$("#id.class").html()

Categories

Resources