loop through and remove form elements in Javascript - javascript

Hi I have been writing a Javascript quiz whilst learning Javascript, but have encountered a problem.
I have one function that dynamically creates the question/answers with radio buttons to mark off the questions.
When I use this second function to attempt to remove the question/answers so I can show the new ones; it removes the text (in p tags) but doesn't remove the radio buttons, even though they also show as children to the form element.
function removeLastQuestions() {
var allQuestions = document.getElementById('questionForm');
for (var i = 0; i < allQuestions.children.length; i++) {
allQuestions.removeChild(allQuestions.children[i]);
}
}
The question/answers and buttons are contained within a form with the id of "questionForm"
I guess I could put the whole form within a div and remove the form, but I'm wondering why looping over them isn't working. I'm trying to do it without using Jquery.
Thanks for any help.

Try this way:
var node = document.getElementById('questionForm');
while (node.hasChildNodes()) {
node.removeChild(node.lastChild);
}
This will remove all form elements.
JSFiddle demo

Related

How to edit elements created with javascript via a loop when click/hover

Can anyone help me? I have many HTML buttons created with Javascript. I want them to delete itself on onclick and change its CSS while hovering your mouse over it, but the "newButton" variable stores the last element from localStorage, which is the last button. With my code, I can only edit the last button. I want the other buttons to delete itself on onclick and change its CSS on hover. I have tried
newButton.onclick=function() {
document.getElementById("list").removeChild(newButton);
localStorage.removeItem(newButton);
}
but it doesn't work well. It only will remove the last button. Although it does, it doesn't remove it from local storage. By the way, the variable "list" is a
< div >, not a < ul >.
Javascript
var list= document.getElementById("list");
function addItemToLocalStorage(){
var newKey=prompt("What key do you want to add to your local storage?");
var newItem=prompt("What value does the key have?");
if (newKey && newItem){
localStorage.setItem(newKey,newItem);
location.reload();
}
}
window.onload=function(){
for (i=0; i<localStorage.length ; i++){
var key=localStorage.key(i);
var lcStorage=localStorage.getItem(key);
var newButton= document.createElement("button");
document.getElementById("list").insertAdjacentElement("beforeend",newButton);
newButton.innerHTML=key+" : "+lcStorage;
newButton.style.padding="20px";
newButton.style.border="lightgray";
newButton.style.fontSize="20px";
newButton.onclick=function(){
list.removeChild(newButton);
localStorage.removeItem(newButton);
}
}
}
If you need anything else just ask me.

Catch all radiobuttons inside a div using jQuery

Someone knows how can I get all the radiobuttons inside a div? The div has a id as follows
<div id="quest{{ $groups }}" class="quest">
I'm using Laravel, therefore my idea is to get the values inside a div, and put in jQuery something like
var radios = $("input[type='radio'][id^='quest'"+groups+"]");
But this doesn´t work, so I want to know how to get all the radiobuttons inside a div an do a loop inside using .each I think.
I need to duplicate one group of questions and then be able to do a validation, but only works for the first group, the second group is not validated and I´ve checked the id value for each radiobutton and change to previousid_2, and the questionnaire is cloned. Also I want to know how can I reset the values when I clone the questionnaire, because if you have select YES NO YES NO, in the second group when you clone it, those results are selected and the disabled fields too.
You're actually asking for several things. Your code implies you have access to the current group in a variable called groups. so...
1) select all radio inputs within a div:
var div = $("div#quest"+groups);
var radiosBtns = div.find("input[type='radio']");
2) Loop over them, and do some work on each element:
var doSomeWork = function(i,radiobtn){
console.log('the value of radio button #' + i ' is ' + radiobtn.value);
};
$.each(radioBtns,doSomeWork);
3) Duplicate a group of radio buttons:
var fromgroup = $("div#quest"+groups);
var togroup = fromgroup.clone();
var insertionPoint = $('body');
var toGroupId = 'questXXX';
// set the ID so it can be targetted
togroup.prop('id',toGroupId);
// reset radio button values
togroup.find('input[type="radio"]').each(function(){
this.prop('checked',false);
});
togroup.appendTo(insertionPoint);
4) Run validation on a specific group
var validateGroup = function(elements){
// your validation logic goes here
var isValid = false;
$.each(function(){
console.log( this.name, this.value );
});
return isValid;
};
// run the validation on the newly inserted group
var targetElements = $("#"+toGroupId).find("input[type='radio']");
var groupIsValid = validateGroup( targetElements );
You can get all radio buttons and iterate on them like following
$("input[type='radio'][id^='quest']").each(function(){
// add your logic here
});
it's very simple using Id's
To get all the elements starting with "quest" you should use:
$("[id^=quest]")
To get those that end with "jander"
$("[id$=quest]")
and the complete answer is
var radios = $("input[type='radio'][id^='quest']");
the point is what if you want to wildcard class :( :(
$("[class^=quest]")
on a dom like
<pre>
<a class="btn quest primary">link</a>
<pre>
it won't work , thus you will need a more complex wildcard that you have to till me when you find it :D
the fact is you will not need it , whenever you need to get a list of element using classes just use a common class :D
hope i helped u well

Can't understand Javascript eventhandler with for loop code

I'm trying to learn JavaScript and I saw a code to change the css style of a web page depending on the button you press.
I can't understand why or how a for loop indicate witch button was press. Here is the javascript part:
var buttons = document.getElementsByTagName("button");
var len = buttons.length;
for (i = 0; i < len; i++) {
buttons[i].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
}
http://jsfiddle.net/qp9jwwq6/
I looked on the net and w3 school but they don't explain that code with a for loop. Can someone explain it to me?
Thank you
Lets break it down.
First we need to have access to the DOM element on the page, so we do that by using a method on the document itself which will return the element we want to manipulate.
var buttons = document.getElementsByTagName("button");
The buttons var will be a list of ALL the buttons on the page. We want to do something with all of them, so first we cache the length of the list, i.e, count how many buttons we have.
var len = buttons.length;
Then we basically say: set i to 0, and step it up one until its equal to the number of buttons we have.
for (i = 0; i < len; i++) {
Now, to access one button from the list, we need to use the brackets notation. So buttons[0] is the first element, buttons[1] is the second, etc. Since i starts at 0, we put i in the brackets so that on each iteration it will access the next button in the list.
buttons[i].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
}
This is equivalent of doing:
buttons[0].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
buttons[1].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
buttons[2].onclick = function() {
var className = this.innerHTML.toLowerCase();
document.body.className = className;
};
// etc.
But of course that is super inefficient, and we may not know how many buttons the page has. So we get all the buttons there, find out how many there are, then go through each button and assign an event handler to it along with a new class.
Now, looking at the onclick handler itself we can see that it first finds the HTML within the button being clicked, turns it into lowercase letters, and assigns it to a variable:
var className = this.innerHTML.toLowerCase();
By using this we're ensuring that each button will know to get it's own innerHTML when clicked. We're not tracking which button is which, we're just telling each button to check it's own content.
Then what it does is change the class of the body HTML element to whatever it is that we just parsed
document.body.className = className;
So say you have something like
<button>success</button>
<button>failure</button>
<button>warning</button>
Clicking the first button would set the <body> element's class to success, clicking the second would set it to failure, and the third would set it to warning.
First line saves all buttons in a variable called buttons. This is actually an array since there can be several buttons on the page. Then you iterate through each button and define a function which should be executed onclick. Lets say you have 2 buttons then it will be buttons[0] and buttons[1] which get the function.
Firstly, speaking generally, the underlying basis for this code is a little wonky and unusual and non-robust, so don't anticipate that you're on the brink of learning any powerful insight into JavaScript or code design.
On to the answer:
The for-loop does not "indicate" which button was pressed. Rather, it loops through every button element on the page and assigns the exact same function definition to the onclick attribute of each element. The code that ends up running when a particular button element is clicked (here I'm talking about the function body) assigns a CSS class to the body element by assigning to document.body.className.
Your question is asking how the function knows which class name to assign to document.body.className. The function grabs the class name from the innerHTML of the button element, which is accessible as this.innerHTML (because in an event handler, this is a reference to the element on which the triggering event occurred). The HTML <button> element is a little bit special, in that, although it is generally a simple-looking button, it is also a non-leaf node, meaning it contains its own HTML. You can put a lot of things in there, but in this example, they just have a plain text node which consists of exactly (or nearly exactly) the class name (Normal for one and Changed for the other). That's how the function can get a CSS class name that is specific to that button; it grabs it from the text inside the clicked <button> element.
I said "nearly exactly" back there because there's actually a letter-case difference between the button text and the actual CSS classes they've defined in the CSS rules (which are normal and changed). That's why they have to lower the letter-case of the extracted button text (toLowerCase()) before assigning the class name. CSS classes are case-sensitive (see Are CSS selectors case-sensitive?).
As I said, this is unusual code. It is rather inadvisable to create a mapping (especially an inexact mapping!) between plain HTML text and code metadata (CSS classes in this case).

Javascript interchange with command button

I am trying to setup an interchange using two texts boxes with a command button in between.
The idea is you type a reference/code in the left hand text box, click the button and it generates an alternative reference/code in the right hand text box.
The point being the user can check alternate bearing references if they can't find what they are looking for with the one they have.
The code I use so far is:
<script type="text/javascript">
oldRef = new Array ("Z582","T608","A173");
newRef = new Array ("C850","S708","X449");
function convert()
{
document.getElementById("v2").value = "";
for (index=0 ; index < oldRef.length ; index++)
{
if ( document.getElementById("v1").value == oldRef[index] )
document.getElementById("v2").value = newRef[index];
}
}
</script>
V1 and V2 refer the the text box ID.
This works with the text boxes but I don't know how to incorporate the command button into this so that they need to click the button in the middle for it to generate.
Any suggestions would be much appreciated.
Best
Will
Its pretty Easy stuff what you need to do is to use onclick of the button like this
document.getElementById('button').onclick = function () {
document.getElementById("v2").value = "";
for (var index=0 ; index < oldRef.length ; index++) {
if (document.getElementById("v1").value == oldRef[index])
document.getElementById("v2").value = newRef[index];
}
}
Here is a demo
I hope this is waht you want....
So essentially there are two things that you need to accomplish what you asked. You need to create a element within your HTML, in this case a button. You then need to catch the event that you want to catch from that element and then execute you convert function.
This is one example of accomplishing this:
So create an button within your HTML
<button id="btn_command">Command</button>
Then in Javascript you want to target that button and add an event listener to that button. In the example the below the variable var btnCommand is set to the html button by using the getElementById method to get that button with that id. Then we add and event listener to that element that when clicked it executes your convert function.
var btnCommand = document.getElementById ("btn_command") ;
btnCommand.addEventListener("click", convert, false) ;
If you want to use jQuery you would do something like this.
$('#btn_command').on('click', function() { convert(); });
Here is another quick and dirty way to just test you button with your function. It is not a best idea to mix your javascript inline with your html but just to test your button and if your convert function is doing that you think you could just say
<button onClick="convert()">Command</button>
Well there are few ways to accomplish what you asked. Happy Coding!

Changing name of all classes in html document with javascript

I have a List that shows Products. When I click on one, I need to change the class of the <li> so as to show that it is clicked. I got this working... But what I can't do is clear the other <li> that have been previously clicked so as to show it is not selected anymore.
This is part of my code, what am I doing wrong? btw, my logic here is to first refresh all classes to notselected, and then just update the list with my product id number. this can be seen on the second line of code.
I'm new to javascript, and did my research, and this is what I got.
function showdetails(ProductID) {
document.getElementsByName("ProductList").className = "notselected";
$("#"+ProductID).attr('class','selected');
Are you trying to do this?
function showdetails(ProductID) {
$("[name=ProductList].selected").removeClass('selected');
$("#"+ProductID).addClass('selected');
}
I think you need to iterate across all elements returned in document.getElementsByName("ProductList") and change className to each element individually.
var productLists = document.getElementsByName('ProductList');
for (i = 0; i < productLists.length; i++) {
productLists[i].className = 'notselected'
}

Categories

Resources