I want to make all my HTML input elements change according to an onclick Javascript function and prevent them from changing again after a click event. My problem is that all the input elements change if only one of them is clicked on. Here is my HTML code:
<input type="button" id="button1" onclick="playerMove('button1')"/><input type="button" id="button2" onclick="playerMove('button2')"/><input type="button" id="button3" onclick="playerMove('button3')"/>
<input type="button" id="button4" onclick="playerMove('button4')"/><input type="button" id="button5" onclick="playerMove('button5')"/><input type="button" id="button6" onclick="playerMove('button6')"/>
<input type="button" id="button7" onclick="playerMove('button7')"/><input type="button" id="button8" onclick="playerMove('button8')"/><input type="button" id="button9" onclick="playerMove('button9')"/>
Here is my Javascript function:
function playerMove() {
document.getElementById("button1").value = "X";
document.getElementById("button1").disabled = "disabled";
document.getElementById("button2").value = "X";
document.getElementById("button2").disabled = "disabled";
document.getElementById("button3").value = "X";
document.getElementById("button3").disabled = "disabled";
document.getElementById("button4").value = "X";
document.getElementById("button4").disabled = "disabled";
document.getElementById("button5").value = "X";
document.getElementById("button5").disabled = "disabled";
document.getElementById("button6").value = "X";
document.getElementById("button6").disabled = "disabled";
document.getElementById("button7").value = "X";
document.getElementById("button7").disabled = "disabled";
document.getElementById("button8").value = "X";
document.getElementById("button8").disabled = "disabled";
document.getElementById("button9").value = "X";
document.getElementById("button9").disabled = "disabled";
}
change your js function like this
function playerMove(button) {
document.getElementById(button).value = "X";
document.getElementById(button).disabled = "disabled";
}
You can do this simply with jQuery:
$("input[type=button]").click(function() {
$(this).attr("disabled", "disabled");
$(this).val("X");
});
This will dynamically add an onclick event listener to each <input type="button" /> to automatically turn on the disabled attribute. No function nor onclick attributes required.
If you don't want to use / don't know how to use jQuery, then here's a plain JS representation of the above code:
var buttons = document.querySelectorAll("input[type=button]");
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function() {
this.disabled = "disabled";
this.value = "X";
});
}
Try using single onclick handler attached to window ; if event.target of click is INPUT element and event.target is not disabled , set event.target value to "x" , disabled property to true
window.onclick = function(e) {
if (e.target.nodeName === "INPUT"
&& /^button\d+$/.test(e.target.id)
&& !e.target.disabled) {
e.target.disabled = true;
e.target.value = "x"
}
}
<input type="button" id="button1" />
<input type="button" id="button2" />
<input type="button" id="button3" />
<input type="button" id="button4" />
<input type="button" id="button5" />
<input type="button" id="button6" />
<input type="button" id="button7" />
<input type="button" id="button8" />
<input type="button" id="button9" />
Consider attaching your event handlers entirely in JavaScript
window.addEventListener('load', function () { // after page loaded (i.e. elements exist)
Array.prototype.forEach.call( // for each
document.querySelectorAll('.my_awesome_buttons'), // of the awesome buttons
function (button) { // call it "button" and do the following
button.addEventListener( // when it gets
'click', // clicked
function (e) { // do your thing to it
this.value = "X";
this.disabled = "disabled";
}
);
}
);
});
<input type="button" id="button1" class="my_awesome_buttons"/><input type="button" id="button2" class="my_awesome_buttons"/><input type="button" id="button3" class="my_awesome_buttons"/>
<input type="button" id="button4" class="my_awesome_buttons"/><input type="button" id="button5" class="my_awesome_buttons"/><input type="button" id="button6" class="my_awesome_buttons"/>
<input type="button" id="button7" class="my_awesome_buttons"/><input type="button" id="button8" class="my_awesome_buttons"/><input type="button" id="button9" class="my_awesome_buttons"/>
element.addEventListener
document.querySelectorAll
Array.prototype.forEach
Which gets Function.prototype.called on a NodeList in this example
Related
I need to write a function that lets you press a button only if you checked a checkbox, this is what I have written so far, it starts as false so the button gets is disabled, but when i check the checkbox it doesn't work
My code :
var gdprAccepted = false
if(gdprAccepted == true){
$('#btn-wheel-submit').prop("disabled", "false");
} else {
$('#btn-wheel-submit').prop("disabled", "true");
}
}
});
}
function gdprChecker() {
if($('#gdprCheck').is(':checked')){
gdprAccepted = true;
console.log(gdprAccepted);
} else {
gdprAccepted = false;
console.log(gdprAccepted);
}
}
You seem to be making this more complex than it needs to be:
function updateButton(checkbox) {
checkbox.form.b0.disabled = !checkbox.checked;
}
<form onsubmit="return false;">
<input type="checkbox" name="cb0" onclick="updateButton(this)"><br>
<button name="b0" disabled onclick="console.log('Enabled')">Button</button>
</form>
You just need to check your checkbox is clicked(enabled). If enable then remove the disabled attribute from button. Like following
var checker = document.getElementById('checkme');
var sendbtn = document.getElementById('buttonId');
// when unchecked or checked, run the function
checker.onchange = function(){
if(this.checked){
sendbtn.disabled = false;
} else {
sendbtn.disabled = true;
}
}
<input type="checkbox" id="checkme"/>
<input type="submit" class="inputButton" disabled="disabled" id="buttonId" value="Button " onclick='alert("enabled")'/>
$(document).ready(function(){
$('#check').click(function(){
if($(this).prop('checked')){
$('#btn').prop('disabled', false);
}else{
$('#btn').prop('disabled', true)
}
})
})
<!-- Using Jquery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check"/>
<input type="submit" disabled="disabled" id="btn" value="Button" onclick='console.log("button is Enabled")' />
var cbox = document.getElementById('check');
var btn = document.getElementById('btn');
cbox .addEventListener('click',function(){
if(cbox.checked){
btn.disabled = false;
}else{
btn.disabled = true;
}
})
<!-- Using Javscript-->
<input type="checkbox" id="check"/>
<input type="submit" class="inputButton" disabled="disabled" id="btn" value="Button" onclick='console.log("button is Enabled")' />
I have the following on jsfiddle. What I need to accomplish is when I click on a button the respective value is inserted in the blank.
https://jsfiddle.net/aminbaig/jefee77L/
Here is the Code:
HTML:
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change()" />
<input type="submit" id="byBtn1" value="Truck" onclick="change()" />
<input type="submit" id="byBtn2" value="Trash" onclick="change()" />
Javascript:
function change() {
var myNewTitle = document.getElementById('myTextField').value;
if (myNewTitle.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = myNewTitle;
}
You can do like this
JS
get the value of the button from the function parameter
function change(value) {
var title = document.getElementById('title');
title.innerHTML = value;
}
HTML
change button type='submit' to type='button', Also pass the value as the function parameter
<input type="button" id="myTextField" value="something" onclick="change(this.value)" />
<input type="button" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="button" id="byBtn2" value="Trash" onclick="change(this.value)" />
DEMO
use like this onclick="change(this.value)" .send the value of the input via click function
function change(val) {
if (val.length == 0) {
alert('Write Some real Text please.');
return;
}
var title = document.getElementById('title');
title.innerHTML = val;
}
There is <span id="title">___________</span> wrong with this world!
<p>
Choose the appropriate word
</p>
<input type="submit" id="myTextField" value="something" onclick="change(this.value)" />
<input type="submit" id="byBtn1" value="Truck" onclick="change(this.value)" />
<input type="submit" id="byBtn2" value="Trash" onclick="change(this.value)" />
I currently have the following code which adds a new input box everytime the user clicks a button. Is there a way to create a button to remove the last generated input box?
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
Push your inputs into an array:
inputs=[];
inputs.push(newContent);
//put this in your addNew function
Now you can get the last element out of that array and remove it
function remove(){
if(inputs.length>0){
elem=inputs.pop();
elem.parentNode.removeChild(elem);
}
}
Add:
<input id="remove" type="button" value="Remove last element" onclick="removeLastElem()" />
And:
function removeLastElem() {
document.getElementById('target').lastChild.remove()
}
EXAMPLE :)
Here is sample of your java-script to remove added div
First you need to create button to remove newly added row
and onclick you need to remove its parent element(last added div).
var data='<label>Temperature (K):</label><input type="number" name="temp"/> <input type="button" value="Remove" onclick="removeDiv(this)" />';
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeDiv(args){
args.parentNode.remove()
}
Sample JSBIN
Simple select last child and remove it
function removeLast(){
document.getElementById("target").lastChild.remove();
}
Here is jsfiddle
https://jsfiddle.net/aqev0pu4/
Put all the content you add to the form in a wrapping node:
var data = '<span><label>Temperature (K):</label><input type="number" name="temp"/></span>'
You can remove the last child of your "target" node:
function removeLast() {
document.getElementById("target").lastChild.remove();
}
Just keep a list of added elements :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedList = [];
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedList.push(document.getElementById('target').appendChild(newContent));
}
function removeLast() {
if (addedList.length) {
document.getElementById('target').removeChild(addedList.pop());
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
If you just want the last element and not a list :
var data = '<label>Temperature (K):</label><input type="number" name="temp"/>'
var addedEl = null;
function addNew() {
var newContent = document.createElement('div');
newContent.innerHTML = data;
addedEl = document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (null !== addedEl) {
document.getElementById('target').removeChild(addedEl);
addedEl = null;
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
Keep track of last inserted input tag with a counter as sub-string of its id and remove the last one by reading the id using counter.
var inputCounter = 1;
function addNew() {
var data = '<label>Temperature (K):</label><input type="number" id="counter' + inputCounter + '" name="temp"/>';
inputCounter++;
var newContent = document.createElement('div');
newContent.innerHTML = data;
document.getElementById('target').appendChild(newContent);
}
function removeLast() {
if (inputCounter > 1) {
inputCounter--;
var last = document.getElementById("counter" + inputCounter).parentElement;
document.getElementById('target').removeChild(last);
} else {
alert("Add new inputs. No last inserted input found.")
}
}
<div id="target"></div>
<input id="add" type="button" value="Add New" onclick="addNew()" />
<input id="remove" type="button" value="Remove last added" onclick="removeLast()" />
im new at this.So, what I want is to hide the RESET button when the clock is working and it should appear when the clock is stoped.same with STOP button that it must only appear when the clock is working.This all must be done with simple and basic Java Script.I dont know about Jquery.
<script language="javascript">
var t1;
var t2;
var t3;
function fn_sample() {
document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
t1 = document.frm.txtS.value;
if(t1>60){
document.frm.txtS.value = 0;
fn_incMin();
}
window.setTimeout("fn_sample()", 1000);
}
function fn_incMin() {
document.frm.txtM.value = parseInt(document.frm.txtM.value) + 1;
t2 = document.frm.txtM.value;
if(t2>60){
document.frm.txtM.value = 0;
fn_incHrs();
}
window.setTimeout("fn_incMin()", 60000);
}
function fn_incHrs() {
document.frm.txtH.value = parseInt(document.frm.txtH.value) + 1;
t3 = document.frm.txtH.value;
window.setTimeout("fn_incHrs()", 3600000);
}
function fn_stop() {
window.clearTimeout(t1);
window.clearTimeout(t2);
window.clearTimeout(t3);
}
function fn_reset() {
document.frm.txtS.value = 0;
document.frm.txtM.value = 0;
document.frm.txtH.value = 0;
}
</script>
</head>
<body>
<form name="frm">
<input type="text" name="txtH" value="0" size="2"/>
<input type="text" name="txtM" value="0" size="2"/>
<input type="text" name="txtS" value="0" size="2"/>
<br /><br />
<input type="button" value="Start" onclick="fn_sample();" />
<input type="button" value="Stop" onclick="fn_stop();" />
<input type="button" value="Reset" onclick="fn_reset();" />
</form>
</body>
You could do like this
<input type="button" value="Start" onclick="fn_sample();this.form.reset.style.display='none'" />
<input type="button" value="Stop" onclick="fn_stop();this.form.reset.style.display='inline'" />
<input type="button" value="Reset" name='reset' onclick="fn_reset();" />
or you coud also use the disable property
<input type="button" value="Start" onclick="fn_sample();this.form.reset.disabled=true" />
<input type="button" value="Stop" onclick="fn_stop();this.form.reset.disabled=false" />
<input type="button" value="Reset" name='reset' onclick="fn_reset();" />
Basically, you'd want to have a onclick property on the buttons like this:
var stopClicked = function(){
document.getElementById("stop").style.display = "none";
document.getElementById("reset").style.display = "";
}
var resetClicked = function(){
document.getElementById("stop").style.display = "";
document.getElementById("reset").style.display = "none";
}
<button onclick='stopClicked()' id='stop'>Stop</button>
<button onclick='resetClicked()' id='reset'>Reset</button>
It's not pretty, but help you undestand whats happends
<script language="javascript">
var t1;
var t2;
var t3;
var st1, st2, st3;
function fn_sample() {
document.getElementById('reset').style.display = 'none';
document.getElementById('start').style.display = 'none';
document.getElementById('stop').style.display = 'inline-block';
running = true;
document.frm.txtS.value = parseInt(document.frm.txtS.value) + 1;
t1 = document.frm.txtS.value;
if(t1>60){
document.frm.txtS.value = 0;
fn_incMin();
}
st1 = window.setTimeout("fn_sample()", 1000);
}
function fn_incMin() {
document.frm.txtM.value = parseInt(document.frm.txtM.value) + 1;
t2 = document.frm.txtM.value;
if(t2>60){
document.frm.txtM.value = 0;
fn_incHrs();
}
st2 = window.setTimeout("fn_incMin()", 60000);
}
function fn_incHrs() {
document.frm.txtH.value = parseInt(document.frm.txtH.value) + 1;
t3 = document.frm.txtH.value;
st3 = window.setTimeout("fn_incHrs()", 3600000);
}
function fn_stop() {
document.getElementById('reset').style.display = 'inline-block';
document.getElementById('start').style.display = 'inline-block';
document.getElementById('stop').style.display = 'none';
window.clearTimeout(st1);
window.clearTimeout(st2);
window.clearTimeout(st3);
}
function fn_reset() {
document.frm.txtS.value = 0;
document.frm.txtM.value = 0;
document.frm.txtH.value = 0;
}
</script>
</head>
<body>
<form name="frm">
<input type="text" name="txtH" value="0" size="2"/>
<input type="text" name="txtM" value="0" size="2"/>
<input type="text" name="txtS" value="0" size="2"/>
<br /><br />
<input id="start" type="button" value="Start" onclick="fn_sample();"style="display:inline-block" />
<input id="stop" type="button" value="Stop" onclick="fn_stop();" style="display:none" />
<input id="reset" type="button" value="Reset" onclick="fn_reset();" style="display:inline-block" />
</form>
</body>
What is inside:
variables st1, st2, st3 are handlers to setTimeout (in your code STOP button doesn't work)
window.setTimeout returns handler to use with clearTimeout
all fields have style proporty which shows or hide buttons on start
document.getElementById('stop') gets element and style.display = 'inline-block'; sets visible on element or hide to hide element
on Start show some buttons and hide unnecessary, on Stop show others and hide unnecessary.
And thats all. In pure JS. this is fiddle to test it: https://jsfiddle.net/6qz30eae/
Hi I have a question how can I upgrade my script that it can disable remaining buttons after you pressed five of them? Now it only count them.
My code:
<input type="Button" onclick="window.increment(event)" value="2"/>
<input type="Button" onclick="window.increment(event)" value="3"/>
<input type="Button" onclick="window.increment(event)" value="4"/>
<input type="Button" onclick="window.increment(event)" value="5"/>
<input type="Button" onclick="window.increment(event)" value="6"/>
<input type="Button" onclick="window.increment(event)" value="7"/>
<input type="Button" onclick="window.increment(event)" value="8"/>
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
Link to js:
https://jsfiddle.net/57js0ps7/6/
Here's as little as possible edited code that works but isn't that readable.
https://jsfiddle.net/90yw1buf/
HTML
<input type="Button" class="bt" onclick="window.increment(event)" value="1"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="2"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="3"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="4"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="5"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="6"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="7"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="8"/>
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
JS
window.increment = function(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
var buttons = document.getElementsByClassName("bt");
var i;
if(window.clicks > 4) {
for (i = 0; i < buttons.length; i++) {
if(buttons[i].clicks != 1) {
buttons[i].disabled = true;
} else {
buttons[i].disabled = false;
}
}
} else {
for (i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
}
}
}
Try not to pollute the global scope (window) because it's a space that all the scripts on your page share, and you should keep shared space clean because you don't know what other scripts might assign a global variable called "click". Read up on closures and scope for some good ideas on how to avoid putting things in the global scope.
You should use classes instead of IDs because IDs must be unique, but classes don't have to be.
It's better to use addEventListener to put event listeners on your elements because an element can only have a single "onclick" function but they can have as many event listeners as they need.
Finally, don't use an anchor (<a>) tag unless it's intended to be clickable, and if it is, you need to include an href attribute`.
(function(){
var clicks = 0;
var buttons = Array.from(document.getElementsByClassName("bt"));
buttons.forEach(btn=>{
btn.addEventListener("click", ()=>{
clicks++;
document.getElementById("clicks").innerText = clicks;
btn.disabled = true;
if(5 === clicks) buttons.forEach(b=>b.disabled = true);
}, false)
});
})();
<input type="Button" class="bt" value="2"/>
<input type="Button" class="bt" value="3"/>
<input type="Button" class="bt" value="4"/>
<input type="Button" class="bt" value="5"/>
<input type="Button" class="bt" value="6"/>
<input type="Button" class="bt" value="7"/>
<input type="Button" class="bt" value="8"/>
<div>
<p>You've choose <span id="clicks">0</span> slot/s.</p>
</div>
I think this is what you are looking for?
var clickedCount = 0;
var arr = [0,0,0,0,0,0,0,0];
function count (buttonNo) {
if (arr[buttonNo-1] == 0) {
clickedCount ++;
arr[buttonNo-1] = 1
}
if (clickedCount >=5) {
var buttons = document.getElementsByTagName('button');
for (var i=0; i < buttons.length; i++) {
if(arr[i]==0){
buttons[i].disabled = 'disabled';
}
}
}
}
<div>
<button onclick="count(1)">button1</button>
<button onclick="count(2)">button2</button>
<button onclick="count(3)">button3</button>
<button onclick="count(4)">button4</button>
<button onclick="count(5)">button5</button>
<button onclick="count(6)">button6</button>
<button onclick="count(7)">button7</button>
<button onclick="count(8)">button8</button>
</div>