Referencing and changing attributes of HTML button inside container - javascript

Below is the HTML code I am playing with. All it does is create an element with two buttons: "Element1" (TitleButton) and "Add". By clicking on "Add" the element is cloned and assigned id="element 2". What I am not able to do is assign value "Element2" for the TitleButton of the cloned element. How can I do it, preferably inside addNode() function? If it is not possible then what are other ways? Thanks
<HTML>
<HEAD>
<TITLE>Dynamically add Textbox, Radio, Button in html Form using JavaScript</TITLE>
<SCRIPT language="javascript">
function addNode(element) {
var adding_element = element.parentNode;
var added_element=adding_element.cloneNode(true);
added_element.setAttribute("id","element 2");
var cont = adding_element.parentNode;
cont.appendChild(added_element);
}
</SCRIPT>
</HEAD>
<BODY>
<FORM>
<div name="container" id="container">
<div name="element 1" id="element 1">
<input type="button" value= "element1"; name="TitleButton" />
<input type="button" value="Add" name="add[]" onclick="addNode(this)" />
</div>
</div>
</FORM>
</BODY>
</HTML>

You can use firstElementChild property.
var id = 2;
function addNode(element) {
var adding_element = element.parentNode;
var added_element = adding_element.cloneNode(true);
added_element.setAttribute("id", "element" + id);
added_element.firstElementChild.setAttribute('value', 'element ' + id);
var cont = adding_element.parentNode;
cont.appendChild(added_element);
id++;
}
http://jsfiddle.net/SUkYg/1/

Related

Hello, My target is, when I hit the button "create checkbox" it will automatically create a checkbox with ID without using input type text

Newbie here. My target is i want to disregard the input type text and add checkbox with id by just clicking the button
<html>
<body>
Enter a Value <input type="text" id="prod" autofocus />
<p>
<input type="button" id="bt" value="Create Checkbox" onclick="createChk(prod)" />
</p>
<p id="container"></p>
</body>
<script>
var i = 1; // COUNTER, FOR CHECKBOX ID.
function createChk(obj) {
if (obj.value !== '') {
var chk = document.createElement('input'); // CREATE CHECK BOX.
chk.setAttribute('type', 'checkbox', 'button'); // SPECIFY THE TYPE OF ELEMENT.
chk.setAttribute('id', 'prodName' + i); // SET UNIQUE ID.
chk.setAttribute('value', obj.value);
chk.setAttribute('name', 'products');
var lbl = document.createElement('label'); // CREATE LABEL.
lbl.setAttribute('for', 'prodName' + i);
// APPEND THE NEWLY CREATED CHECKBOX AND LABEL TO THE <p> ELEMENT.
container.appendChild(chk);
container.appendChild(lbl);
obj.value = '';
document.getElementById(obj.id).focus();
i = i + 1;
}
}
</script>
</html>
See the snippet here: https://www.encodedna.com/javascript/practice-ground/default.htm?pg=create_checkboxes_using_javascript1
i hope i have understand your question correctly
this code will add a checkbox, regardless of the text input value
all was removed is the if statement
<!DOCTYPE html>
<html>
<head>
<title>Add Checkbox Dynamically using JavaScript</title>
</head>
<body>
Enter a Value <input type="text" id="prod" autofocus />
<p>
<input type="button" id="bt" value="Create Checkbox" onclick="createChk(prod)" />
</p>
<p id="container"></p>
</body>
<script>
var i = 1; // COUNTER, FOR CHECKBOX ID.
function createChk(obj) {
var chk = document.createElement('input'); // CREATE CHECK BOX.
chk.setAttribute('type', 'checkbox'); // SPECIFY THE TYPE OF ELEMENT.
chk.setAttribute('id', 'prodName' + i); // SET UNIQUE ID.
chk.setAttribute('value', obj.value);
chk.setAttribute('name', 'products');
var lbl = document.createElement('label'); // CREATE LABEL.
lbl.setAttribute('for', 'prodName' + i);
// CREATE A TEXT NODE AND APPEND IT TO THE LABEL.
lbl.appendChild(document.createTextNode(obj.value));
// APPEND THE NEWLY CREATED CHECKBOX AND LABEL TO THE <p> ELEMENT.
container.appendChild(chk);
container.appendChild(lbl);
obj.value = '';
document.getElementById(obj.id).focus();
i = i + 1;
}
</script>
</html>

How do I get the parent id in this function?

The attached code properly returns the id and the value of the checked box.
I need to get the id of the enclosing div so that I can set the display attribute to hidden.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123" onclick='doClick();'><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456" onclick='doClick();' onclick='doClick();'><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789" onclick='doClick();'><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
<script>
function doClick() {
var checkedValue = null;
var inputElements = document.getElementsByName('cb');
for(var i=0; inputElements[i]; ++i){
if(inputElements[i].checked){
checkedValue = inputElements[i].value;
checkedID = inputElements[i].id;
console.log('checked id = '+checkedID);
console.log('value = '+checkedValue);
break;
}
}
ParentID = checkedID.offsetParent;
console.log(ParentID.id);
}
</script>
</html>
I expected that ParentID would return the id. Instead, I get an error "TypeError: undefined is not an object (evaluating 'ParentID.id')"
You need to remove the onevent attributes and use either an onevent property or event listener instead:
<input doClick()...>
This is basically what you need to hide the parent element of clicked element (event.target):
event.target.parentElement.style.display = 'none';
Demo
Details commented in demo
// Reference the form
var form = document.forms[0];
// Register the form to the change event
form.onchange = hide;
/*
Called when a user unchecks/checks a checkbox
event.target is always the currently clicked/changed tag
Get the changed parent and set it at display: none
*/
function hide(e) {
var changed = e.target;
changed.parentElement.style.display = 'none';
console.log(`Checkbox: ${changed.id}: ${changed.value}`);
console.log(`Parent: ${changed.parentElement.id}`);
}
<!DOCTYPE html>
<html>
<head></head>
<body>
<div id="wrapper">
<form>
<div id="boatdiv1"><input type="checkbox" name="cb" id="boat1" value="123"><label for='boat1'>boat1</label><br></div>
<div id="boatdiv2"><input type="checkbox" name="cb" id="boat2" value="456"><label for='boat2'>boat2</label><br></div>
<div id="boatdiv3"><input type="checkbox" name="cb" id="boat3" value="789"><label for='boat3'>boat3</label><br></div>
</form>
</div>
</body>
</html>
Use parentNode - also note that checkedID is a string, so it doesn't have a parent. Use getElementById to get the checked input:
ParentID = document.getElementById(checkedID).parentNode;
console.log(ParentID.id);

HTML input into Javascript variable

I've been attempting to grab text input from HTML and trying to output the text back into HTML but for some reason it does not seem to be working. Does putting input within a form alter the interaction with getElementById or is it possible that the second button usage of formaction is interrupting this?
$(document).ready(function(){
$("#submit").on("click",function(){
var test = document.getElementById("searchInput");
$("#text").html(test);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type ="text" id ="searchInput"><br>
<button id = "submit">Search</button>
<button formaction="https://en.wikipedia.org/wiki/Special:Random" formtarget="_Blank">Random</button>
</form>
<div id = "text">
<h1>test</h1>
</div>
EDIT: I have attempted to change
var test = document.getElementById("searchInput");
to
var test = document.getElementById("searchInput").value;
previously and it is still not working. Is there an interaction that is failing that I am missing? Also I would like to be able to store the input as variable i.e thats why I am purposely putting it into a variable before outputting it.
EDIT2: There wasn't anything particularly wrong about the code other than retrieving the value. I am currently using codepen.io to code and did not load jquery into the pen.
Since you're using jQuery, it will make more sense to use jQuery to obtain the elements' value:
Use this to always replace #text element contents with #searchInput value:
$("#text").html($("#searchInput").val());
Use this to append #searchInput value to #text element:
$("#text").append($("#searchInput").val());
But the whole logic does not make any sense. You are changing an elements' value that it is outside the form you are submitting. Either you should prevent submit button click event from submitting the form, or have the #text element inside the form as an input, textarea or hidden field:
$(document).ready(function(){
$("#submit").on("click",function(e) {
e.preventDefault();
$("#text").html($("#searchInput").val());
})
});
or having the #text element inside the form for submitting:
<form>
<input type="hidden" id="text" name="text">
<input type ="text" id ="searchInput"><br>
<button id = "submit">Search</button>
<button formaction="https://en.wikipedia.org/wiki/Special:Random" formtarget="_Blank">Random</button>
</form>
You Using form element, so once you click the button , the form will be reloaded, if you want to display textbox value to the element , once remove the form element.
<input type ="text" id ="searchInput"><br>
<button id = "submit">Search</button>
<button formaction="https://en.wikipedia.org/wiki/Special:Random" formtarget="_Blank">Random</button>
<div id ="text">
<h1 id="welc"></h1>
</div>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#submit").on("click",function(){
var test = $('#searchInput').val();
$("h1").html(test);
});
});
</script>
Just Remove tag, and check it.
You need to find the element's value and then set it as HTML.
$("#text").html(test.value);
I have updated your question mate check this one .
$(document).ready(function(){
$("#submit").on("click",function(){
var test = document.getElementById("searchInput").value;
$("#text").html(test);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type ="text" id ="searchInput"><br>
<button id = "submit">Search</button>
<button formaction="https://en.wikipedia.org/wiki/Special:Random" formtarget="_Blank">Random</button>
</form>
<div id = "text">
<h1>test</h1>
</div>
I think this will work for you.
<! doctype HTML>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form>
<input type="text" id="searchInput">
<br>
<button type="button" id="submit">Search</button>
<button formaction="https://en.wikipedia.org/wiki/Special:Random" formtarget="_Blank">Random</button>
</form>
<div id="text">
<h1>test</h1>
</div>
</body>
<script>
$(document).ready(function () {
$("#submit").on("click", function () {
$("#text").html($("#searchInput").val());
})
});
</script>
</html>
Edit your JS code please try:
EDIT:
$(document).ready(function(){
$("#submit").on("click",function(){
var test = $("#searchInput").val();
$("#text").html(test);
})
});

Add Radio buttons to Html form using Javascript or Jquery

In my HTML code I have
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<button type="button"onclick="monthlytimesheets()">Submit</button>
</form>
In my Javascript file I have the following:-
function monthlytimesheets() {
$.post('http://localhost:8000/timer/monthly_timesheet/',
function(returnedData) {
for(i=0;i<returnedData.length;i++) {
for(j=i+1;j<returnedData.length;j++) {
if(returnedData[i]['id']==returnedData[j]['id']) {
returnedData.splice(j,1)
}
}
}
});
Now i want my returnedData[i]['full_name'] rendered on html page as radio buttons. How can i do that. How do you dynamically create radio buttons from JS? Also can i assign values to these radio buttons?
you can create radio buttons easily using jquery as you want. I wrote a code to show how to create radio button dynamically. automatically and when a button clicked.change the inside conditions as your needs. try below code.
<html>
<head></head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<body>
<!-- Example one , add radio button using jquery automatically-->
<h1>Example one , add radio button using jquery automatically</h1>
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<div class="lastone"></div>
</form>
<br><br><hr>
<!-- Example two, add radio button using jquery when button click-->
<h1>Example two, add radio button using jquery when button click-</h1>
<form id="approveone">
<input name="myDate" id="monthYearPicker" />
<div class="lasttwo"></div>
<input type="button" id="addradio" value="submit">
</form>
</body>
<script type="text/javascript">
$(document).ready(function(){
for(var i=0;i<5;i++)
{
var labelname = "radio button"+i;
var value = i;
var create = $('<input type="radio" value="'+value+'"><label>'+labelname+'</label><br>');
$(".lastone").append(create);
}
});
$(document).ready(function(){
$("#addradio").click(function(){
for(var i=0;i<9;i++)
{
var labelname = "radio button"+i;
var value = i;
var create = $('<input type="radio" value="'+value+'"><label>'+labelname+'</label><br>');
$(".lasttwo").append(create);
}
});
});
</script>
</html>
You can create elements dynamically like this
var content = document.createElement('div');
var newElement = document.createElement('input');
newElement.setAttribute('type', 'radio');
newElement.value = "Your value"; ///Here you can assigned value to the radio button
content.appendChild(newElement);
Create a function that returns a radio element. Similar question was already asked.
It can be found here: How do you dynamically create a radio button in Javascript that works in all browsers?
function createRadioElement(name, checked) {
var radioHtml = '<input type="radio" name="' + name + '"';
if ( checked ) {
radioHtml += ' checked="checked"';
}
radioHtml += '/>';
var radioFragment = document.createElement('div');
radioFragment.innerHTML = radioHtml;
return radioFragment.firstChild;
}
Note that this is the snipped from the answer of the posted link, published by Prestaul.
Would have postet it as comment, but need 50rep to comment...
function monthlytimesheets()
{
var name = $('#monthYearPicker').val();
$('#approve').append('<input type="radio" />'+name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form id="approve">
<input name="myDate" id="monthYearPicker" />
<button type="button"onclick="monthlytimesheets()">Submit</button>
</form>

Create a new <div> with .createElement()

Hi I'm new to Javascript, having problem creating and adding a new to the DOM. (I want to do this with native javascript not jquery).
When I click the "Calculate" button, I very briefly see the Text flash on the screen and then disappear. Nothing added to the DOM.
Here is my JS script:
function makeResponseBox() {
document.getElementById("calculate").onclick = function()
{
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
}//close function (makeResponseBox)
window.onload=makeResponseBox;
Here is my HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Add Element to DOM</title>
<script src="calculate.js"></script>
</head>
<body id="main">
<h1>Add Element to DOM</h1>
<form id ="form">
<fieldset>
<input type="submit" value="Calculate" id="calculate" />
</fieldset><!-- close fieldset -->
</form><!-- close form -->
</body>
</html>
It's because the form is submitted so the page is reloaded
You need to add a parameter to your listener , say function(e) and call e.preventDefault() at the beginning of the listener.
example:
document.getElementById("calculate").onclick = function(e)
{
e.preventDefault();
var responseBox = document.createElement("DIV"); //create <div>
var para = document.createElement("P");//create <p>
var text = document.createTextNode("Text");//
para.appendChild(text);//append text to para
var newDiv = responseBox.appendChild(para);// append <p> to <div> and assign to variable
document.body.appendChild(newDiv);//append as child to <body>
}
Or you could also change the type of your button to remove the submit function
<input type="button" value="Calculate" id="calculate" />
But then your <form> become useless and you could remove it
change your submit type to button which will avoid the reload
<input type="submit" value="Calculate" id="calculate" />
to
<input type="button" value="Calculate" id="calculate" />
and if you want to submit the form handle it from js

Categories

Resources