How to change the label of a checkbox in JavaScript? - javascript

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.

Related

How to replace an input box with a dropdown in Vanilla JS

I am trying to replace an input box with Vanilla JS. Currently I am using jquery to do this like so.
column.replaceWith("<select id='" + column[0].id + "' name='" + column[0].id + "' class='" + column[0].className + "'></select>");
I am refactoring all my code into Vanilla JS and this is the last thing I need to do. I have done the document.createElement('select'); and that creates the <select></select> element. I then tried to do;
newEl.innerHTML += '<select id="selBidReceivedIsPM" name="selBidReceivedIsPM">'
+ '<option value="0">AM</option>'
+ '<option value="1">PM</option>';
,
but this doesn't create the id or name. I've been googling and trying things for the last 3 hours and need some help figuring this out.
html:
<label for="columnA5"></label>
<input
type="number"
id="columnA5"
name="columnA5"
class="columnA"
step="any"
>
Something like this should work to create select with options having value and innerHTML.
var select = document.createElement('select');
select.id="selBidReceivedIsPM"
select.name="selBidReceivedIsPM"
var val=2;
var time=["AM","PM"];
for (var i = 0; i<val; i++){
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = time[i];
select.appendChild(opt);
}
console.log(select)
I think, if DOM element is not created by javascript but rendered You can't "delete" it (in Your case input type="number"...).
You can "replace" it by "hiding" input and place select element on "his" place.
There is example, try it :
function replaceEle() {
var txt=document.getElementById('columnA5');
/*
or You can use querySelectorAll :
var txt=document.querySelectorAll('input[type="number"]');
then You'll get all textboxes in page, and then You have to use for loop
*/
var sel=document.createElement('select'); //create select element
sel.id='selBidReceivedIsPM';
sel.setAttribute('onchange','alert(this.value)');
/*show selected value, or instead alert You can type some JS
function, what gonna do when option is changed */
var opt=document.createElement('option'); //create option element
opt.value=0;opt.innerHTML='AM';
sel.appendChild(opt); //add option element into select element
opt=document.createElement('option');
opt.value=1; opt.innerHTML='PM';
sel.appendChild(opt);
sel.selectedIndex=0; //set default selected value
txt.style.display='none'; //hide input element
txt.parentNode.insertBefore(sel, txt); //insert select element just before input,
}
<input type="number" id="columnA5" value=""/><br>
<input type="button" value="Replace it" onclick="replaceEle();"/>

Adding code to div clears input val

I have a JS function that adds divs of the class PizzaBox to an empty div called PizzaBoxHolder. Why is it that whenever a new line is created, the user-inputted values in the inputs are replaced with the placeholders? Also, as a side note, should I even be using a place holder for a color input?
function newBox
{
numOfBoxes += 1; //This is a global variable declared elsewhere, other functions use it but only this one modifies it
var pizzaBoxCode = "<div class = 'PizzaBox'>"
+ " <h6>Box number " + numOfBoxes + "</h6>"
+ " <p>Color: <input type = 'color' class = 'boxColor' placeholder = '#000000'/></p>"
+ " <p>Toppings: <input type = 'text' class = 'toppings' placeholder = 'Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>"
+ "</div>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder") //Empty div until this function fills it up
PizzaBoxHolder.innerHTML += pizzaBoxCode;
}
Any help is appreciated. Thanks!
The way you're currently doing it, is resetting the entire innerHTML of your main PizzaBoxHolder element. By resetting the HTML, you're losing the current values. If you change the code to create an element, and then call .appendChild, it'll work as expected. The reason is, you're only appending a node to the current element.
var pizza = document.createElement("div");
pizza.className += "PizzaBox";
pizza.innerHTML = "<h6>Box number " + numOfBoxes + "</h6><p>Color: <input type='color' class='boxColor' placeholder = '#000000'/></p><p>Toppings: <input type='text' class='toppings' placeholder='Anything but anchovies or mushroom! Never anchovies or mushroom!'/></p>";
var PizzaBoxHolder = document.getElementById("PizzaBoxHolder");
PizzaBoxHolder.appendChild(pizza);
Working fiddle.

jQuery: Make dynamic content editable after submission

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();
});

Get value of dynamically created textbox using JavaScript

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);
}

Firing a function on click

I have addBanner() function shown below which is invoked every time I click addBanner button. This adds a input field and fires the ausu auto-suggestion jQuery script.
When I click addBanner() Button I get a input field and auto-suggestion works fine. Suppose I click addBanner() button again it adds another empty Input Field and auto-suggestion works fine for that too as the auto-suggest function is fired every time I click addBanner Function. But, if I want to edit the first Input Field which I had added there's conflict. Please tell me how to get the control back to the first input field.
var bnrc = 1;
var bnrl = 5;
function addBanner(divName){
if (bnrc == bnrl) {
alert("You have reached the limit of adding " + bnrc + " Banner companies.");
}
else {
var newdiv = document.createElement('div');
newdiv.className = "banner_sugg";
newdiv.innerHTML = (bnrc + 1) + ". <input type='text' value='' name='banner[]' id='banner" + (bnrc + 1) + "' autocomplete='off' /> <input type='hidden' value='' name='bannerID[]' id='bannerID" + (bnrc + 1) + "' autocomplete='off' />";
document.getElementById(divName).appendChild(newdiv);
bnrc++;
}
$.fn.autosugguest({
className: 'banner_sugg',
methodType: 'POST',
minChars: 1,
rtnIDs: true,
dataFile: 'e_data.php'
});
}
Did you spell suggest wrong on purpose? I'm spelling it correctly below so you may need to alter it.
You are currently (re)calling $.fn.autosuggest({}) every time you add a new item, which may be breaking the previous items.
Try:
$(newDiv).autosuggest({})
So it only adds autosuggest functionality to the new div. And you should move the code above into the section where you create the newDiv as it's even being called on error.

Categories

Resources