I am trying to make the innerHTML of a single button (amongst various buttons) the value of an input.
I have an empty div inside a form and six buttons (each with the same class).
<form>
<div id='wrapper'></div>
<button type='submit'>Submit</button>
</form>
<div class="col-lg-6 Div1">
<button class="form-button" onclick="addForm()">Button 1</button>
<button class="form-button" onclick="addForm()">Button 2</button>
<button class="form-button" onclick="addForm()">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button" onclick="addForm()">Button 4</button>
<button class="form-button" onclick="addForm()">Button 5</button>
<button class="form-button" onclick="addForm()">Button 6</button>
</div>
And then I have a dynamically added inputs, a button and a div. The inputs and buttons gets added into the div (.innerDiv) which get's added inside the #wrapper div (in the html code). The reason is so that the remove button can remove everything from it's parent element without removing all the dynamically added tags.
i = 1;
addForm() {
if(i < Infinity) {
var innerDiv = document.createElement('div');
innerDiv.classList = 'innerDiv' + i;
$('.wrapper').append(innerDiv);
//This adds a fixed input
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName' +i;
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
$(".form-button").click(function() { dynamicInput.value = this.innerHTML; }); //Gives the innerHTML of the button that was clicked as the value of the input
$('.innerDiv' + i).append(dynamicInput);
var anotherInput = document.createElement('input');
anotherInput.type = 'text';
anotherInput.name = 'anotherInput' +i;
anotherInput.classList = 'anotherInputClass';
anotherInput.placeholder = 'Write name here';
$('.innerDiv' + i).append(anotherInput);
var removeButton = document.createElement('button'); //This removes one element inside a parent div.
removeButton.type = 'button';
removeButton.classList = 'remove';
removeButton.innerHTML = '-';
removeButton.onclick = function () {
this.parentElement.remove();
}
$('.innerDiv').append(removeButton);
i++;
}
}
I've fixed the function for the dynamicInput to what was suggested to me by s.Bergmann. So whenever a button with the class of .form-button is clicked, all the above stiff will be added and the dynamicInput will have a fixed value of the button that was clicked. If I click Button 5 and then Button 2, in code, it will look a little something like this:
<form>
<div id='wrapper'>
<div class='innerDiv1'>
<input type='text' name='dynamicInputName1' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput1' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
<div class='innerDiv2'>
<input type='text' name='dynamicInputName2' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput2' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
</div>
<button type='submit'>Submit</button>
</form>
As you can see, each button added one div, with the two inputs and the button. However, both inputs that were created from the dynamicInput have the same value (Button 2.). The idea is, if I press Button 5 first the first dynamicInput should have a value = 'Button 5' and if I then press Button 2, the second dynamicInput should have a value = 'Button 2' (These inputs are the first input of each div).
I'm not sure this is what you're going for,
but it might nudge you in the right direction.
It seems that onclick on a .form-button two things should happen:
it should create a dynamic input element
addForm() should be called // or perhaps addForm is what creates the input element?
If i were you, i'd reconsider the need for that "dynamic element". why not just use the actual button clicked?
anyway...
$(".form-button").click(function () { // replaces all the onlick=
addForm(this);
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName';
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
dynamicInput.value = this.innerText;
console.log("Dynamic input", dynamicInput.value);
});
function addForm (formButton) { // dummy function? unclear what it's used for.
console.log("Form Button:", formButton)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 Div1">
<button class="form-button"> Button 1</button>
<button class="form-button">Button 2</button>
<button class="form-button">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button">Button 4</button>
<button class="form-button">Button 5</button>
<button class="form-button">Button 6</button>
</div>
Related
I want to make a div tag invisible when the page loads and make it visible everytime a button is clicked. This is what I have on my page:
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
Whenever AddItem button is clicked, I want to display one Div tag/item so if I click "Add Item" button, I want to make visible only div tag "realProp1", now if I click "AddItem" button again, I want to make visible "realProp2" div tag. Below is what I have, the code is working for one div tag, but not for several div tags:
<script>
window.onload = function () {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function Additem() {
document.getElementById("realProp1").style.display = "";
};
</script>
How can I make one div tag visible at each button click.
You can use :eq() to compare which div to show and save some variable for holding the last count value or you can just use $("div[id^=realProp]").filter(":hidden").first().show() for filtering the hidden divs and showing first div always.
Demo Code :
$('div[id^=realProp]').hide();
var count = 0;
$('.show_div').on('click', function() {
$('div[id^=realProp]:eq(' + count + ')').show(); //show div
count++; //for next div to show
//or without count ..use below
//show first div..by filtering hidden divs
//$("div[id^=realProp]").filter(":hidden").first().show();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" class="btn btn-primary show_div">Add Item</button>
Without jquery :
var length = document.querySelectorAll("div[id^='realProp']").length;
var count = 1; //for holding last visible div count
function AddItem() {
if (count <= length) {
document.getElementById("realProp" + count).style.display = "block"; //show..
count++;
} else {
console.log("No more divs")
}
};
div[id^='realProp'] {
display: none
}
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
let count = 1;
window.onload = function() {
document.getElementById("realProp1").style.display = 'none';
document.getElementById("realProp2").style.display = 'none';
document.getElementById("realProp3").style.display = 'none';
};
function AddItem() {
for (let i = 1; i < 4; i++) {
document.getElementById("realProp" + i).style.display = "none";
}
document.getElementById("realProp" + count).style.display = "";
if (count <3 ){
count++;
} else {
count = 1;
}
};
<div id="realProp1">
<input name="FirstName[0]" class="form-control" />
</div>
<div id="realProp2">
<input name="FirstName[1]" class="form-control" />
</div>
<div id="realProp3">
<input name="FirstName[2]" class="form-control" />
</div>
<button type="button" onclick="AddItem()" class="btn btn-primary">Add Item</button>
I tried this code but it doesn't work.
This is my Html code
<div class="left-container1">
<button class="ui button " value="right" id="answer1">yes</button>
<button class="ui button " value="wrong" id="answer2">no</button></div>
</div>
<div class="navigation-controllers ">
<button onclick="displayAnswer1()" class="ui button next " id="next" >next</button>
</div>
and this my JavaScript code
var button1 = document.getElementById("answer1");
var button2 = document.getElementById("answer2");
function displayAnswer1() {
if (button1.click == true){
location.href="./2_2.html";
};
if (button2.click == true){
location.href="./2_1.html";
} ;
}
I want when I click the next button, it will redirect to the page based on the chosen "Yes" or "No" button.
How to solve this issue?
Why don't use data-attribute like:
document.querySelectorAll('button[data-href]').forEach(el =>{
el.addEventListener('click', () => {
displayAnswer(el);
});
});
function displayAnswer(el) {
const link = (el.dataset.href === '1') ? './2_2.html' : './2_1.html';
console.log(link);
//location.href = link; comment because here don't work.
}
<div class="left-container1">
<button class="ui button " value="right" data-href='1' id="answer1">yes</button>
<button class="ui button " value="wrong" data-href='2' id="answer2">no</button>
</div>
And instead of use inline event i suggest you to learn addEventListener.
Reference:
data-attribute
addEventListener
querySelectorAll
forEach
You need to use input radio buttons for this.
Use the .checked property to find out which one is selected.
var button1 = document.getElementsByName("choice");
var button2 = document.getElementById("answer2");
function displayAnswer1() {
// console.log(button1.value);
if (button1[0].checked){
// location.href="./2_2.html";
console.log("right");
}
else if (button1[1].checked){
//location.href="./2_1.html";
console.log("wrong");
}
}
<div class="left-container1">
<input type="radio" class="ui button " value="right" id="answer1" name="choice">yes</button>
<input type="radio" class="ui button " value="wrong" id="answer2" name="choice">no</button></div>
</div>
<div class="navigation-controllers ">
<button onclick="displayAnswer1()" class="ui button next " id="next" >next</button>
</div>
You can ' store ' the clicked button in a variable. And check that.
let clickedButton = ''
const myButtons = document.querySelectorAll('.my-btn')
myButtons.forEach(btn => btn.onclick = function() {
clickedButton = btn.id
})
function displayAnswer1() {
if (clickedButton === 'answer1') {
console.log('clicked1')
//location.href = "./2_2.html";
};
if (clickedButton === 'answer2') {
console.log('clicked2')
//location.href = "./2_1.html";
};
}
<div class="left-container1">
<button class="ui button my-btn " value="right" id="answer1">yes</button>
<button class="ui button my-btn " value="wrong" id="answer2">no</button>
</div>
<div class="navigation-controllers ">
<button onclick="displayAnswer1()" class="ui button next " id="next">next</button>
</div>
You have to add event listeners to the buttons. I have modified your code and attached event listeners. Please check.
var button1 = document.getElementById("answer1");
var button2 = document.getElementById("answer2");
button1.addEventListener("click", function(){
console.log("going to page 2");
window.location = "./2_2.html";
});
button2.addEventListener("click", function(){
console.log("going to page 1");
window.location="./2_1.html";
});
<div class="left-container1">
<button class="ui button " value="right" id="answer1">yes</button>
<button class="ui button " value="wrong" id="answer2">no</button></div>
</div>
<div class="navigation-controllers ">
<button onclick="displayAnswer1()" class="ui button next " id="next" >next</button>
</div>
I have a function which onclick displays the form.
Was wondering if there is any efficient way to code instead of creating 4 different functions for 4 different forms? Below example is for 4 forms but I am working with multiple forms.
<div class="navbar">
<div class="dropdown">
<button class="dropbtn" onclick="myFunction1()">Category 1
<i class="fa fa-caret-down"></i>
</button>
</div>
//Same for other 3 categories
<div id="form1" style = "display:none">
<form action="#" method="post" id="demoForm1" class="demoForm1" >
<fieldset>
<legend>Use CTRL to select multiple options</legend>
<p>
<select name="demoSel[]" id="demoSel" size="4" multiple>
<option value="ABC">ABC</option>
</select>
<input type="submit" value="Submit" />
<textarea name="display" id="display" placeholder="view select list value(s) onchange" cols="20" rows="4" readonly></textarea>
</p>
</fieldset>
</form>
</div>
//Same for other 3 forms
<script>
function myFunction1() {
document.getElementById("form1").style.display = '';
}
function myFunction2() {
document.getElementById("form2").style.display = '';
}
function myFunction3() {
document.getElementById("form3").style.display = '';
}
function myFunction4() {
document.getElementById("form4").style.display = '';
}
</script>
It's generally not a good idea to use inline event handlers.
Next, add a data-* attribute to each button and remove the onclick attribute like:
<button class="dropbtn" data-target="form1">...</button>
<button class="dropbtn" data-target="form2">...</button>
<button class="dropbtn" data-target="form3">...</button>
<button class="dropbtn" data-target="form4">...</button>
Then, you can use .addEventListener() on these buttons with class dropbtn and update respective form element display property like:
const btns = document.querySelectorAll(".dropbtn");
btns.forEach(function(btn) {
btn.addEventListener("click", function(cbox) {
document.getElementById(this.dataset.target).style.display = '';
});
});
Demo:
const btns = document.querySelectorAll(".dropbtn");
btns.forEach(function(btn) {
btn.addEventListener("click", function(cbox) {
document.getElementById(this.dataset.target).style.display = '';
});
});
<button class="dropbtn" data-target="form1">Form 1</button>
<button class="dropbtn" data-target="form2">Form 2</button>
<br><br>
<form id="form1" style="display:none">Form 1 Content Here</form>
<form id="form2" style="display:none">Form 2 Content Here</form>
Don't use on-event attributes:
<button onclick='eventHandler()'></button>
Use event listeners or on-event properties:
const btn = document.querySelector('button');
btn.addEventListener('click', eventHandler);
// OR
btn.onclick = eventHandler;
If you have multiple targets to click -- register the click event to a parent tag that all target tags share.
document.querySelector('main').onclick = toggleForm;
Instead of using .style on each <form> toggle classes
// CSS
.off { display: none }
// JavaScript
forms[idx].classList.toggle('off');
Demo
Note: Details are commented in demo
/*
- Reference the parent tag (<main>)
- Register <main> to the click event
- Event handler function toggleForm() is called on click
*/
document.querySelector('main').onclick = toggleForm;
// Event handler always passes Event Object (event)
function toggleForm(event) {
// Collect all <form>s into a HTML Collection
const forms = document.forms;
// Collect all <button> into a NodeList
const buttons = document.querySelectorAll('button');
// Reference the tag the user clicked (<button>)
const clicked = event.target;
// if a <button> was clicked...
if (clicked.matches('button')) {
// ...toggle the <button>'s .on and .off classes
clicked.classList.toggle('off');
clicked.classList.toggle('on');
/*
- Convert buttons NodeList into a rel Array
- Iterate through the buttons array and return
the index of the clicked <button>
*/
let idx = [...buttons].flatMap((button, index) => clicked === button ? [index] : []);
/*
- Toggle the .off class on the <form> located at the
index that was obtained from the previous statement
*/
forms[idx].classList.toggle('off');
}
}
button {
display: inline-block;
width: 11ch
}
button.off::before {
content: 'Show '
}
button.on::before {
content: 'Hide '
}
form.off {
display: none
}
<main>
<button class='off' type='button'>A</button>
<button class='off' type='button'>B</button>
<button class='off' type='button'>C</button>
<button class='off' type='button'>D</button>
<hr>
<form id='A' class='off'>
<fieldset>
<legend>Form A</legend>
</fieldset>
</form>
<form id='B' class='off'>
<fieldset>
<legend>Form B</legend>
</fieldset>
</form>
<form id='C' class='off'>
<fieldset>
<legend>Form C</legend>
</fieldset>
</form>
<form id='D' class='off'>
<fieldset>
<legend>Form D</legend>
</fieldset>
</form>
</main>
I have 2 <div>s of at least 81 buttons, all with the same class, but they have different ids and names. I am trying to figure out how to alert the name of the current button that was being pressed.
function runMe(e){
return function(){
console.log(e.getAttribute("id"));
}
}
var eles = document.getElementsByClassName("myButton")
Array.prototype.forEach.call(eles,function(ele){
ele.onclick = runMe(ele);
})
<button id="a1" class="myButton">A1</button>
<button id="b2" class="myButton">B2</button>
Get all the buttons with the same class name and assign the click event listener to each buttons so that when you click the button the listener is invoked:
function btnClick(){
console.log(this.id + " " + this.name);
}
var allButtons = document.getElementsByClassName('myButton');
for(i=0; i<allButtons.length; i++){
allButtons[i].addEventListener('click', btnClick);
}
<button id="1" class="myButton" name='name1'>B1</button>
<button id="2" class="myButton" name='name2'>B2</button>
<button id="3" class="myButton" name='name3'>B2</button>
<button id="4" class="myButton" name='name4'>B2</button>
<button id="5" class="myButton" name='name5'>B2</button>
You can try the following way by using this.name inside the click handler function:
var btns = document.querySelectorAll('button');
btns.forEach(function(btn){
btn.addEventListener('click', function(){
console.log('Name of the cliked button is:', this.name)
})
})
<div>
<button type="button" id="btn1" name="btnName1">Button 1</button>
<button type="button" id="btn2" name="btnName2">Button 2</button>
<!--------- More Buttons--------->
</div>
<div>
<!--------- More Buttons--------->
<button type="button" id="btn48" name="btnName48">Button 48</button>
<button type="button" id="btn49" name="btnName49">Button 49</button>
<button type="button" id="btn50" name="btnName50">Button 50</button>
<!--------- More Buttons--------->
</div>
I'm doing a project for parent with a newborn Child, where they can progress in their learning taking care of their Child. This will be shown with buttons, and when a stage is complete, it will change the color on that button.
My code so far looks like this:
To change the buttons color to green.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button" value = "Instructed" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done with help" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done by yourself" style= "color:black" onclick="setColor('button', '#101010')";/>
</div>
</div>
When I Click the first button "Instructed" the color change to green (As I want it to). But when I click anyother button, the first button once again goes green and the other goes blue?
How can I fix it so whatever button they click on, will be colored green?
You gave every button the same id - an id should be identifying, which in this case it isn't. Your code here, takes the first element with the id button which is why the first button changes everytime.
Either use different ids for each individual button, or access the clicked element itself through the event-variable.
You also have only one count-variable, which won't work with multiple buttons. Imagine you pressing the first button => count is now 1. You then press the second button, it wouldn't turn green, as count is already 1.
You should probably store that information on the element itself, probably with a data-count-attribute.
Here is a working example:
function setColor(element) {
if(!element.hasAttribute('data-count')){
element.setAttribute('data-count', 1);
}
var count = element.getAttribute('data-count');
if(count == 0){
element.style.backgroundColor = '#ffffff';
element.setAttribute('data-count', 1);
}else{
element.style.backgroundColor = '#7fff00';
element.setAttribute('data-count', 0);
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" value = "Instructed" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done with help" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done by yourself" style= "color:black" onclick="setColor(this)";/>
</div>
</div>
So lets remove those duplicate ID's, and then we can actually pass the element into the function directly so we don't need to grab it by it's ID.
Then instead of using a count variable, we store value on the actual element in a data attribute so that it's state is stored on the element itself.
function setColor(element) {
if (element.getAttribute('data-done') === "0") {
element.style.backgroundColor = "#7FFF00"
element.setAttribute('data-done', "1");
} else {
element.style.backgroundColor = "#FFFFFF"
element.setAttribute('data-done', "0");
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button1" value="Instructed" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button2" value="Done with help" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button3" value="Done by yourself" style="color:black" onclick="setColor(this)" data-done="0" />
</div>
</div>
Although perhaps the most semantic way would be to use classes and add an event listener:
// Grab all the buttons by their class
var btns = document.querySelectorAll('.btn-diaper');
// Loop through the buttons
for (var i = 0; i < btns.length; i++) {
// Assign a click listener to each button
btns[i].addEventListener("click", function(event) {
var el = event.toElement;
// Toggle the "active" class, which changes the button styling
if (el.classList.contains('active')) {
el.classList.remove('active');
} else {
el.classList.add('active');
}
});
}
.btn-diaper {
color: black;
background-color: #fff;
}
.btn-diaper.active {
background-color: #7fff00;
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input class="btn-diaper" type="button" id="button1" value="Instructed" />
<input class="btn-diaper" type="button" id="button2" value="Done with help" />
<input class="btn-diaper" type="button" id="button3" value="Done by yourself" />
</div>
</div>