I was going to use jQuery mobile for this one to get the mobile theme http://jsfiddle.net/hhken790/
HTML
<input type="button" value="-" class="qtyminus" />
<input type="text" name="myInputs[qty][]" value="0" class="qty" />
<input type="button" value="+" class="qtyplus" />
jQuery
$("#dynamic").on("click", ".qtyplus", function (e) {
e.preventDefault();
var $input = $(this).prev("input");
var currentVal = parseInt($input.val());
if (!isNaN(currentVal)) {
$input.val(currentVal + 1);
} else {
$input.val(0);
}
});
However, the plus and minus wont work here. Any idea what causing this?
When you add jQM, it enhances/styles many DOM elements by adding container divs and other DOM elements. This means that your buttons and text inputs are no longer siblings in the DOM and prev() will not work. Instead traverse up the DOM and then down:
var $input = $(this).closest("div#dynamic").find(".qty");
e.g:
$("#dynamic").on("click", ".qtyplus, .qtyminus", function (e) {
e.preventDefault();
var $input = $(this).closest("div#dynamic").find(".qty");
var currentVal = parseInt($input.val());
if (!isNaN(currentVal)) {
$(this).hasClass("qtyplus") ? $input.val(currentVal + 1) : $input.val(currentVal - 1);
} else {
$input.val(0);
}
});
Updated FIDDLE
Related
I have 2 buttons, one + and one - that increments the quantity of items.
I also have a "Price" of the item and a span that displays the price of the item.
What i need is: When the user clicks the + or - buttons, it increments the quantity of items and the total price.
So far my code looks like this:
HTML:
<input type="number" size="4" class="input-text qty text" title="Cantidad" value="1" name="quantity" min="1" step="1">
<input type="button" class="plus" value="+">
<input type="button" class="minus" value="-">
<span class="price">90.00 €</span>
JS
function inc() {
var price = "price";
var elems = document.getElementsByTagName('*'), i;
for (i in elems) {
var a = document.getElementsByName("quantity")[0].value;
if((' ' + elems[i].className + ' ').indexOf(' ' + price + ' ') > -1) {
var valOfItem = parseInt(elems[i].innerHTML);
var x = a * valOfItem;
elems[i].innerHTML = x;
}
}
}
I haven't tried it yet but i guess everything will be working as soon as i add my func() to the onClick event on those buttons, i was hoping to do it with jQuery after the document is done loading but i'm not sure how.
Any ideas?
Why not just use javascript (in head) to disable the buttons until page load?
<script language="text/javascript">
window.addEventListener("plus", function() { document.getElementById('plus').disabled = false; }, false);
window.addEventListener("minus", function() { document.getElementById('minus').disabled = false; }, false);
</script>
Then have the buttons disabled by default.
<input type="button" class="plus" value="+" disabled="disabled">
<input type="button" class="minus" value="-" disabled="disabled">
The downside of this is any non-JS users will be unable to use the site. Then again, that's likely the case already.
You can add click event handlers to .plus and .minus and calculate sum based on input value using .text() and .val():
Fiddle.
$(document).ready(function()
{
var basePrice = parseFloat($(".price").text());
$(".plus").click(function()
{
changeValue(1);
});
$(".minus").click(function()
{
changeValue(-1);
});
function changeValue(sign)
{
$("[name='quantity']").val(parseInt($("[name='quantity']").val()) + sign);
var countValue = $("[name='quantity']").val();
var newValue = (basePrice * countValue).toFixed(2);
$(".price").text(newValue);
}
});
I'm trying to get a range slider to work but I can't.
How do I add an event handler so when the user chooses a value my code reads that value. Right now its value is always 1.
I would like to do this using pure Javascript.
HTML:
<div id="slider">
<input class="bar" type="range" id="rangeinput" min="1" max="25" value="1" onchange="rangevalue.value=value"/>
<span class="highlight"></span>
<output id="rangevalue">1</output>
</div>
JAVASCRIPT:
var rangeInput = document.getElementById("rangeinput").value;
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
if (rangeInput > 0 && rangeInput < 5) {
alert("First");
} else {
alert("Second");
}
}
JSFIDDLE
Single Read
The problem is that you're only reading the value once (at startup), instead of reading it every time the event occurs:
// this stores the value at startup (which is why you're always getting 1)
var rangeInput = document.getElementById("rangeinput").value;
You should be reading the value in the handler instead:
function testtest(e) {
// read the value from the slider:
var value = document.getElementById("rangeinput").value;
// now compare:
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Or to rewrite your code:
var rangeInput = document.getElementById("rangeinput");
var buttonInput = document.getElementById("btn");
if (buttonInput.addEventListener) {
buttonInput.addEventListener("click", testtest, false);
}
else if (buttonInput.attachEvent) {
buttonInput.attachEvent('onclick', testtest);
}
function testtest(e) {
var value = rangeInput.value;
if (value > 0 && value < 5) {
alert("First");
} else {
alert("Second");
}
}
Updating rangevalue
It also looks like you want to update the output element with the value of the range. What you're currently doing is referring to the element by id:
onchange="rangevalue.value=value"
However, as far as I know, this isn't standard behavior; you can't refer to elements by their id alone; you have to retrieve the element and then set the value via the DOM.
Might I suggest that you add a change listener via javascript:
rangeInput.addEventListener("change", function() {
document.getElementById("rangevalue").textContent = rangeInput.value;
}, false);
Of course, you'll have to update the code to use addEventListener or attachEvent depending on the browsers that you want to support; this is where JQuery really becomes helpful.
Use the mouseup event for that.
var rangeInput = document.getElementById("rangeinput");
rangeInput.addEventListener('mouseup', function() {
if (this.value > 0 && this.value < 5) {
alert("First");
} else{
alert("Second");
}
});
DEMO: http://jsfiddle.net/ZnYjY/1
You can also use the FORMs oninput method:
<form oninput="result.value=parseInt(a.value)+parseInt(b.value)">
<input type="range" name="b" value="50" />100 +
<input type="number" name="a" value="10" /> =
<output name="result"></output>
</form>
This has an advantage over onclick/onmouseup because it handles the case where the slider is moved using the keyboard (tab to the input and use the arrow keys)
Use the oninput event.
HTML Codes:
<div id="slider">
<input class="bar" type="range" id="range-input" min="1" max="25" value="1"/>
<span class="highlight"></span>
<output id="range-value">1</output>
</div>
<button id="btn" type="submit">Submit</button>
Javascript scripts
(function() {
var rangeInput = document.getElementById("range-input")
var rangeValue = document.getElementById("range-value")
var button = document.getElementById("btn")
// Show alert message when button clicked
button.onclick = testTest
function testTest() {
let value = rangeInput.value
if(value > 0 && value < 5) {
alert("first")
return true
}
alert("second")
return false
}
// Print the range value to the output
rangeInput.oninput = rangeOutput
function rangeOutput() {
rangeValue.innerText = rangeInput.value
}
})()
Demo
UPDATE 2021
Another option is to use the input event handler i.e. eventTarget.addEventListener("input", alert("Hello World"), though this event handler is the same with oninput, the difference having we can use addEventListener
<script type="text/javascript">
function range()
{
//the simplest way i found
var p = document.getElementById('weight');
var res = document.getElementById('rangeval');
res.innerHTML=p.value+ " Lbs";
}
</script>
<label for="weight">Your weight in lbs:</label>
<input name="weight" type="range" id="weight" max="500" min="0" value="75" onChange="range()" onKeyUp="range()">
<span id="rangeval"></span>
I am having the following HTML block in my page.
<input type="text" id="fillingInput"/>
<input type="text" id="filledInput" maxlength="5"/>
<input type="button" onclick="$('#filledInput').val($('#fillingInput').val());"/>
when the button is clicked, the value of fillingInput is set as value for filledInput.
But the maxlength is not considered while setting value like this.
Any solution?
Try slice:
<input type="button"
onclick="$('#filledInput').val($('#fillingInput').val().slice(0,5));"/>
Try this
$(document).ready(function () {
$('#add').click(function () {
var str = $('#fillingInput').val();
if (str.length > 5) {
str = str.substring(0, 5);
$('#filledInput').val(str);
}
});
});
one way to get this is ... removing all charaters after 5th character. using substring()
<input type="button" id="add" />
JS
$('#add').click(function(){
var str=$('#fillingInput').val();
if(str.length > 5) {
str = str.substring(0,5);
}
$('#filledInput').val(str);
});
fiddle ..
it is recommended not to use inline javascript.
if you are using jQuery you can add a "valHook" which hooks into each call of .val()
$.valHooks.input = {
set: function(element, value) {
if ("maxLength" in element && value.length > element.maxLength)
value = value.substr(0, element.maxLength);
element.value = value;
return true;
}
};
By using relative references I am able to remove items which have been added to the list within a specfic part of the form. For example, by adding a requirement it can be deleted just from the requirement.
My issue is two fold:
Adding an item to references adds it to all three categories
When I try to add values to the other sections (qualifications) it says my input was blank.
http://jsfiddle.net/spadez/9sX6X/60/
var container = $('.copies'),
value_src = $('#current'),
maxFields = 10,
currentFields = 1;
$('.form').on('click', '.add', function () {
value_src.focus();
if ($.trim(value_src.val()) != '') {
if (currentFields < maxFields) {
var value = value_src.val();
var html = '<div class="line">' +
'<input id="accepted" type="text" value="' + value + '" />' +
'<input type="button" value="X" class="remove" />' +
'</div>';
$(html).appendTo(container);
value_src.val('');
currentFields++;
} else {
alert("You tried to add a field when there are already " + maxFields);
}
} else {
alert("You didn't enter anything");
}
})
.on('click', '.remove', function () {
value_src.focus();
$(this).parents('.line').remove();
currentFields--;
});
Is it possible to modify this code without repeating it for each section, by using relatively references such as "parent" for example. I want to use this same script for all three sections but have it so each list is independant.
I'm new to javascript so I was wondering if this is possible because I only managed to get it working on the delete.
You have to use this to get the current element. In your case this refers to the button which was clicked.
The next step is to get the input box which belongs to the button. E.g. $(this).prev(); like in this example:
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
http://jsfiddle.net/9sX6X/62/
The same is also true for your appending part. Your are appending your html to all three elements which match $('.copies'). Instead you have to try to get there from this.
$('.form').on('click', '.add', function () {
var value_src = $(this).prev();
var copies = $(this).parent().prev();
http://jsfiddle.net/9sX6X/63/
I would suggest adding a wrapping div to each section.
<div class="section">
<h4>Requirements</h4>
<div class="copies"></div>
<div class="line">
<input id="current" type="text" name="content" placeholder="Requirement" />
<input type="button" value="Add" class="add" />
</div>
</div>
Then you can do this:
var $section = $(this).closest(".section");
$(html).appendTo($section.find(".copies"));
This will add to just the related .copies element instead of to all .copies as your code does now. A similar approach can be used for all other elements as well.
I want to stop the user to check another checkbox after a certain number of checkboxes have been checked already. i.e. After 3 checkboxes are checked, the user cannot check anymore and a message says 'You're not allowed to choose more than 3 boxes.'
I'm almost there but the last checkbox is still being checked and I don't want that, I want it to be unchecked with the message appearing.
How do I do that:
var productList = $('.prod-list'),
checkBox = productList.find('input[type="checkbox"]'),
compareList = $('.compare-list ul');
productList.delegate('input[type="checkbox"]', 'click', function () {
var thisElem = $(this),
thisData = thisElem.data('compare'),
thisImg = thisElem.closest('li').find('img'),
thisImgSrc = thisImg.attr('src'),
thisImgAlt = thisImg.attr('alt');
if (thisElem.is(':checked')) {
if ($('input:checked').length < 4) {
compareList.append('<li data-comparing="' + thisData + '"><img src="' + thisImgSrc + '" alt="'+ thisImgAlt +'" /><li>');
} else {
$('input:checked').eq(2).attr('checked', false);
alert('You\'re not allowed to choose more than 3 boxes');
}
} else {
var compareListItem = compareList.find('li');
for (var i = 0, max = compareListItem.length; i < max; i++) {
var thisCompItem = $(compareListItem[i]),
comparingData = thisCompItem.data('comparing');
if (thisData === comparingData) {
thisCompItem.remove();
}
}
}
});
I might have misunderstood the question... see my comment.
Too prevent the selection, you can call event.preventDefault() and define the handler with the event parameter.
$('input[type="checkbox"]').click(function(event) {
if (this.checked && $('input:checked').length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});
DEMO
Alternatively, set this.checked to false. This will even prevent the browser from rendering the checkmark.
DEMO
one single jquery function for multiple forms
<form>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg" ><br>
<input type="checkbox" name="seg"><br>
<input type="checkbox" name="seg"><br>
</form>
<br><br><br><br><br>
<form>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1" ><br>
<input type="checkbox" name="seg1"><br>
<input type="checkbox" name="seg1"><br>
</form>
$('input[type="checkbox"]').click(function(event) {
if ($("input[name= "+ this.name +"]:checked").length > 3) {
event.preventDefault();
alert('You\'re not allowed to choose more than 3 boxes');
}
});