I have multiple buttons on my page with css qtyButton:
I want to add the css to only button where value matches with the given value. I have used the following code but it is giving me error undefined in the alert box when i try to select the button value.
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>
$(document).on('click','.arrow',function(e){
var curr_qty=$('#qty').val();
var text = $('.qtyButton').filter(function () {
return this.value== curr_qty}).css('color', 'blue');
});
The issue is with this.value - the button doesn't have a .value - your HTML implies that you want to check the .text() of the button (or use this.innerText for more efficiency):
$("#clickme").click(function(e) {
var curr_qty = $('#qty').val();
$('.qtyButton').filter(function() {
return $(this).text() == curr_qty
}).css('color', 'red'); // changed to red as blue wasn't clear enough
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type='text' id='qty' value="1" />
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>
<hr/>
<button id='clickme'>click me</button>
You need to use .innerText instead .value
return this.innerText == curr_qty
Assuming you have, somewhere in your DOM, a <button> with the class arrow, and a number <input> with the ID qty.
I want to respect your return this.value== curr_qty line, so I added value attributes to your .qtyButton elements.
<button class="arrow" type="button">.arrow</button>
<input type="number" id="qty" value="1">
<br />
<button class="qtyButton" value="1" >1</button>
<button class="qtyButton" value="2" >2</button>
<button class="qtyButton" value="3" >3</button>
$(document).on('click','.arrow',function(e) {
$('.qtyButton').css('color', '');
var curr_qty = $('#qty').val();
var text = $('.qtyButton').filter(function () {
return this.value == curr_qty;
}).css('color', 'blue');
});
I added a color reset of all elements before your logic.
$(document).on('click', function(e) {
var curr_qty = 2
$('.qtyButton').each(function() {
if (parseInt($(this).text()) === curr_qty) $(this).css('color', 'blue')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="qtyButton">1</button>
<button class="qtyButton">2</button>
<button class="qtyButton">3</button>
Related
Hi how can I make a button that will increase and decrease a value? I the button to add 1 when clicked once and reduced the value by 1 when clicked again so it can't count to more than 1.
I have around 50 buttons and currently, it resets when I choose more than 2 buttons, but it has to add all the values of the buttons that were clicked once. Site around it looks similar to this:
var clicks = 0;
function clickME() {
clicks += 1;
if (clicks == 2) {
clicks = 0;
}
document.getElementById("clicks").innerHTML = clicks;
}
<input type="Button" id="bt" />
Considering each button (or more generically each element) is part of the DOM (Document Object Model), each one is an object, so no one makes you unable to use them: you can set the field clicks for each button DOM object:
function clickME(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;
}
Checking out your code, I also simplified your logic replacing the if to check zero with the MOD (%) operator. Furthermore I replaced innerHTML with innerText because the number we won't to be rendered as HTML code, but as plain text, although in this case, it doesn't make difference.
Note:
Don't forget to pass the event data object with the onclick attribute in HTML:
<input onclick="clickME(event)" ...>
Check out this fiddle:
https://jsfiddle.net/57js0ps7/2/
You need to maintain a counter per each button individually - use an array to keep track of how many times a button has been clicked. If you don't the clicks var in your code will be two when you select 2 buttons and reset.
On your html:
lets say you have 50 of these
<button type="button" data-clicked="false">1</button>
<button type="button" data-clicked="false">2</button>
and on your javascript
var buttons = document.querySelectorAll('button');
buttons.forEach(function(button) {
button.addEventListener('click', function() {
if (this.dataset.clicked == 'false') {
this.dataset.clicked = 'true';
this.innerHTML = parseInt(this.innerHTML) + 1;
}
else {
this.dataset.clicked = 'false'
this.innerHTML = parseInt(this.innerHTML) - 1;
}
})
});
EDIT: Here is a working fiddle
Since you have this tagged as jQuery here is a solution using jQuery. The solution involves using the data- attribute to hold the click count for each button (input). Not sure why you use inputs instead of buttons, but I kept that the same
It also has a getTotal() function that goes through each element and tallies the click to see how many slots were selected and displays that number for you.
$(document).ready(function() {
$(".btn").on("click", clickME);
});
function clickME() {
var clicks = $(this).data("clicks");
var newClicks = parseInt(clicks) + 1;
if(newClicks > 1){
newClicks = 0;
}
// set the new click count on the element
$(this).data("clicks", newClicks);
setTotal();
}
function setTotal(){
var total = 0;
$(".btn").each(function(imdex, btn) {
var currClicks = parseInt($(btn).data("clicks"));
total += currClicks;
});
$("#clicks").text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="Button" class="btn" data-clicks=0 value="0" />
<input type="Button" class="btn" data-clicks=0 value="1" />
<input type="Button" class="btn" data-clicks=0 value="2" />
<input type="Button" class="btn" data-clicks=0 value="3" />
<input type="Button" class="btn" data-clicks=0 value="4" />
<input type="Button" class="btn" data-clicks=0 value="5" />
<input type="Button" class="btn" data-clicks=0 value="6" />
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
In my code
<script>
$(document).ready(function(){
$("#btn").on('click', function() {
var caretPos = document.getElementById("txt").selectionStart;
var textAreaTxt = $("#txt").val();
var txtToAdd = $("#btn").val();
$("#txt").val(textAreaTxt.substring(0, caretPos) + txtToAdd + textAreaTxt.substring(caretPos) );
})
});
</script>
HTML
<textarea id="txt" rows="15" cols="70"></textarea>
<input type="button" id="btn" value="OK" />
<input type="button" id="btn" value="Bye" />
<input type="button" id="btn" value="TC" />
I want to give these values in textarea. But it is only giving value of Ok button. How I can give each button values in textarea
You have the same id on elements. ID's must be unique. You can use class and end to this:
$(".btn").on('click', function() {
$("#txt").val(this.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="txt" rows="5" cols="10"></textarea>
<input type="button" class="btn" value="OK" />
<input type="button" class="btn" value="Bye" />
<input type="button" class="btn" value="TC" />
try this
html
<textarea id="txt" rows="15" cols="70"></textarea>
<input type="button" id="btn" value="OK" />
<input type="button" id="btn" value="Bye" />
<input type="button" id="btn" value="TC" />
javascript
$('input#btn').click(function()
{
$('#txt').val($('#txt').val()+this.value); // append the value of each button
})
Demo here
<textarea name="insert" rows="5" cols="30" id="insert" onblur="myFunction()"></textarea>
<button class="myvalue" id="myvalue">Ok</button>
<button class="myvalue" id="myvalue">Bye</button>
<button class="myvalue" id="myvalue">Tc</button>
<script>
function insertAt (myField, myValue, startSel, endSel)
{
if (startSel || startSel == '0') {
var startPos = startSel;
var endPos = endSel;
myField.val(myField.val().substring(0, startPos)+ myValue+ myField.val().substring(endPos, myField.val().length));
}` else {
myField.val() += myValue;
}`}var targetBox = $('textarea#insert'),
startSel,
endSel;`targetBox.bind('focusout', function() {
startSel = this.selectionStart;
endSel = this.selectionEnd;
});
$(".myvalue").click(function() {
var myValue = $(this).text();
insertAt(targetBox, myValue, startSel, endSel);
});
</script>
Finally It Works
All your buttons have the same 'id', and 'OK' is the first one, so that's the one that's being returned...
To get the value of the button that's clicked you'd need to give each one a unique id (which should be the case anyway).
I would put your buttons in a separate container, probably a div, and apply the click handler to that. In the handler function, see if the event target has a value attribute, and if it has, send it to your textbox.
Or you could give each button a handler, it depends on your circumstances...
Danny
My suggestion to you change button id to class because id is unique for each element so you have to use class instead of id.
$("input.btn").on('click', function() {
$("#txt").val($("#txt").val()+$(this).val());
})
Demo
I'm just a beginner in JavaScript and I'm having trouble what kind of function I should use.
This is what I want to do, if I click any buttons in the choices, the value of the button that I choose will be transferred to the button that no value in it and I can also delete the value that I choose in the black button. It is like playing 4pics 1word.
Here is the sample: jsfiddle
<form>
<button class="inputx" id="input1" maxlength="1">E</button>
<button class="inputx" id ="input2" maxlength="1">X</button>
<button class="inputx" id ="input3" maxlength="1"></button>
<button class="inputx" id = "input4" maxlength="1"></button>
<button class="inputx" id = "input5" maxlength="1"></button>
<button class="inputx" id = "input6" maxlength="1"></button>
<button class="inputx" id = "input7" maxlength="1"></button>
<button id="get">Check</button>
</form>
<form>
<h3>Choices</h3>
<button value ="X" maxlength="1">X</button>
<button value ="E" maxlength="1">E</button>
<button value ="M" maxlength="1">M</button>
<button value ="A" maxlength="1">A</button>
<button value ="P" maxlength="1">P</button>
<button value ="E" maxlength="1">E</button>
<button value ="L" maxlength="1">L</button>
</form>
I've updated the Fiddle with a working example.
http://jsfiddle.net/RF867/11/
The main idea is that when a .letter is clicked we want to fill the first empty .inputx with the clicked letter. And remove it once the .inputx is clicked.
$('.letter').click(function(){
$('.inputx:empty').first().html($(this).html());
return false;
});
$('.inputx').click(function(){
$(this).empty();
return false;
});
Here's a working fiddle : http://jsfiddle.net/RF867/10/
I have first add an id to the second form so i could target it easier.
Then some minor change to the validation function. By minor, i mean changing the this.value to this.innerHTML.
Then i created these 2 functions. Read the comment to understand :
$('#letters button').click(function(e){ // The new id, target buttons
e.preventDefault(); //Prevent page reload
if($('.inputx:empty:first').text($(this).val()).length) //Change the text of the first empty button. Then check if it changed something
$(this).hide(); //If it changed something, hide the button
})
$('.inputx').click(function(e){ //To remove character on click
e.preventDefault();
if($(this).is(':not(:empty)')){ //If there is text in the button
var letter = $(this).text(); //Get the letter
$('#letters button:not(:visible)').filter(function(){ //Select only visible buttons
return this.value == letter; //Check if the value is the same as the letter
}).first().show(); //There is multiple instance of the same letter (like e), select the first and show
$(this).empty(); //Remove the value of the button
}
}).not(':empty').each(function(){ //select button that has text by default
var letter = $(this).text();
$('#letters button:visible').filter(function(){
return this.value == letter;
}).first().hide(); //Hide default button
})
Check the updated fiddle. I added following function for click on the texts. I have made some changes in buttons to make the fiddle work without post request.
$('.temp').on('click',function(e){
var filled = false;
e.preventDefault();
var s = $(this).text();
$(".inputx").each(function(){
if(!filled)
{
if($(this).text() == "")
{
$(this).text(s);
filled = true;
}
}
});
});
The variable filled is boolean and is used to fill only first empty textbox. Hope this helps you.
i have made some changes and now the code works perfectly
HTML:
<div>
<button class="inputx" id="input1" maxlength="1">E</button>
<button class="inputx" id ="input2" maxlength="1">X</button>
<button class="inputx" id ="input3" maxlength="1"></button>
<button class="inputx" id = "input4" maxlength="1"></button>
<button class="inputx" id = "input5" maxlength="1"></button>
<button class="inputx" id = "input6" maxlength="1"></button>
<button class="inputx" id = "input7" maxlength="1"></button>
<button id="get">Check</button>
<button id="clean">Clean</button>
</div>
<div class="btnsChoices">
<h3>Choices</h3>
<button value ="X" maxlength="1">X</button>
<button value ="E" maxlength="1">E</button>
<button value ="M" maxlength="1">M</button>
<button value ="A" maxlength="1">A</button>
<button value ="P" maxlength="1">P</button>
<button value ="E" maxlength="1">E</button>
<button value ="L" maxlength="1">L</button>
</div>
JS:
$('#get').on("click", function(e){
e.preventDefault();
var a='';
$('.inputx').each(function(){
a += $(this).text();
});
if (a.toUpperCase() === "EXAMPLE") {
alert("success");
}
else{
alert("wrong");
}
});
$("#clean").on("click",function(){
$(".inputx").text("");
});
$(".btnsChoices button").on("click", function(){
var newValue = $(this).val();
$(".inputx").each(function(){
if($(this).text() == ""){
$(this).text(newValue);
return false;
}
});
});
and i update your jsfiddle: http://jsfiddle.net/RF867/12/
See http://jsfiddle.net/RF867/15/
The check has been removed for now, but I hope you find the following a little cleaner to work with:
<div id="scratchpad">
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
<button></button>
</div>
<button id="get">Check</button>
<div id="choices">
<h3>Choices</h3>
<button value="X">X</button>
<button value="E">E</button>
<button value="M">M</button>
<button value="A">A</button>
<button value="P">P</button>
<button value="E">E</button>
<button value="L">L</button>
</div>
JavaScript to go with the new HTML
$('#scratchpad button').click(function(e) {
var letter = $(this).text();
if (letter === '') {
// do nothing
} else {
//re-enable choice
$('#choices button[value=' + letter + ']:empty:first').text(letter);
//clear button
$(this).text('');
}
});
$('#choices button').click(function(e){
var letter = $(this).text();
if (letter === '') {
// do nothing
} else {
// place choice
$('#scratchpad button:empty:first').text(letter);
// empty button letter
$(this).text('');
}
});
When I press ADD, I show the hidden #box, I hide the ADD button and show the REMOVE button.
html:
<input type="button" id="add" value="ADD">
<input type="button" class="no-display" id="remove" value="REMOVE">
<div class="no-display" id="box">
<input id="a" value="" type="text" />
<input id="b" value="" type="text" />
<input id="c" value="" type="text" />
</div>
jquery:
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
see working DEMO
Now, I want to check if the input fields #a or #b or #c have a value. If they have a value, on pageload I want to show #box, hide the #add button and show the #remove button.
What is the best way to do this?
you can see a DEMO here (not finished)
using filter() to get the count of the input that has value on it... if count is greater that 0 ..means atleast one input is not empty so.. hide add, show remove buttons and the container
try this
$('#add,#remove').click(function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
});
var count = $('#a,#b,#c').filter(function () {
return $(this).val().length > 0;
}).length;
if (count > 0) {
$('#box').show();
$('#add').hide();
$('#remove').show();
}
updated as per comment
var count = $('#a,#b,#c').filter(function () {
return this.value.length > 0; //faster
}).length;
working fiddle
Try this: Move toggle code to a function. Bind it to the click. Call it on load if any of the inputs have a value.
$(function () {
var toggleBox = function () {
$('#add').toggle();
$('#remove').toggle();
$('#box').slideToggle("fast");
};
$('#add,#remove').click(toggleBox);
if(!!$("#a, #b, #c").filter(function() {return this.value;}).length) {
toggleBox();
}
});
I have a webpage. There is a button called add. When this add button is clicked then 1 text box must be added. This should happen at client side only.
I want to allow the user to add at most 10 text boxes.
How can I achieve it using javascript?
example:
only 1 text box is displayed
user click add >
2 text boxes displayed
user clicks add >
I also wants to provide a button called "remove" by which the user can remove the extra text box
Can anyone provide me a javascript code for this??
Untested, but this should work (assuming an element with the right id exists);
var add_input = function () {
var count = 0;
return function add_input() {
count++;
if (count >= 10) {
return false;
}
var input = document.createElement('input');
input.name = 'generated_input';
document.getElementbyId('inputs_contained').appendChild(input);
}
}();
add_input();
add_input();
add_input();
A solution using the jQuery framework:
<form>
<ul class="addedfields">
<li><input type="text" name="field[]" class="textbox" />
<input type="button" class="removebutton" value="remove"/></li>
</ul>
<input type="button" class="addbutton" value="add"/>
</form>
The jQuery script code:
$(function(){
$(".addbutton").click(){
if(".addedfields").length < 10){
$(".addedfields").append(
'<li><input type="text" name="field[]" class="textbox" />' +
'<input type="button" class="removebutton" value="remove"/></li>'
);
}
}
// live event will automatically be attached to every new remove button
$(".removebutton").live("click",function(){
$(this).parent().remove();
});
});
Note: I did not test the code.
Edit: changed faulty quotation marks
I hope you are using jQuery.
<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript"><!--
$(document).ready(function(){
var counter = 2;
$("#add").click(function () {
if(counter==11){
alert("Too many boxes");
return false;
}
$("#textBoxes").html($("#textBoxes").html() + "<div id='d"+counter+"' ><label for='t2'> Textbox "+counter+"</label><input type='textbox' id='t"+counter+"' > </div>\n");
++counter;
});
$("#remove").click(function () {
if(counter==1){
alert("Can u see any boxes");
return false;
}
--counter;
$("#d"+counter).remove();
});
});
// --></script>
</head><body>
<div id='textBoxes'>
<div id='d1' ><label for="t1"> Textbox 1</label><input type='textbox' id='t1' ></div>
</div>
<input type='button' value='add' id='add'>
<input type='button' value='remove' id='remove'>