Calculation issue With JQuery - javascript

I know it is very simple.But Still it is not working.I am multiplying a input number with a fixed number,but is not showing the expected result.it always shows the Error message "Please enter some value" even i enter some integer e.g. 6.
This is Html Code.
<input type="text" class="cc" id="getdata" />
<div id="result"> <input type="text" id="show" /></div>
<input type="button" value="calculate" id="calculate" />
This is JQuery Code.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#input").val() != '' && $("#input").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#input").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});
Any help will be highly appreciated.
Can anyone tell me please how to concatenate all clicked values of different buttons in a textbox?I want to show previous and current clicked value of button in a textbox.
Thank you.

Do you not mean #getdata? Where is #input?
Replace ("#input") with ("#getdata") in your code.
Check out this fiddle.
$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
} else {
$("#result").html("Please enter some value");
}
});
});​

You have no input whose id is "input". The jquery selector #somestring is looking for an element whose id is somestring.
Replace ("#input") by ("#getdata") in your code.

There is no field with the ID input in the HTML you posted, yet your jQuery is looking for one. Perhaps you meant $('#show')
With jQuery issues, ALWAYS suspect the selector before even wondering what else might be wrong. Confirm it actually finds the elements you think it does - never assume.
console.log($('#input').length); //0

if ($("#input").val() != '' && $("#input").val() != undefined) {
You dont have any field anywhere in your markup with the id input!
I think you intended all the instances of #input in that script to be #getdata, but you should also only read its value once into a variable and use that:
$("#calculate").click(function () {
var val = $('#getdata').val();
if (val != '' && val != undefined) {
$("#result").html("total value is::" + parseInt(val) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
Live example: http://jsfiddle.net/82pf4/

$(document).ready(function () {
$("#calculate").click(function () {
if ($("#getdata").val() != '' && $("#getdata").val() != undefined) {
$("#result").html("total value is::" + parseInt($("#getdata").val()) * 5);
}
else {
$("#result").html("Please enter some value");
}
});
});

Checkout this Fiddle
I think that is what you want.
<input type="text" class="cc" id="getdata" />
<input type="button" value="calculate" id="calculate" />
<div id="result"></div>​
<script>
$("#calculate").click(calculate);
$("#getdata").keypress(function(ev){
if(ev.keyCode == 13)
calculate();
});
function calculate()
{
var $getData = $("#getdata");
var $result= $("#result");
if ($getData .val() != '' && $getData .val() != undefined && !isNaN($getData .val()))
{
$result.append((parseInt($getData .val()) * 5) + "<p>");
}
else
{
$result.append("Please enter some value<p>");
}
$getData .val("").focus();
}
​
</script>

Related

jQuery - How do I use AND with Selector?

My code's function is to alert user if the ptype textfield is empty.
$("input[name*='ptype']").each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
However, I need to add another criteria where another field amount is not 0. So that the function get triggered when ptype="" && amount!=0. I'm very new in jQuery, and I'm not sure how to use AND operator in here. I've tried to do some based on other questions but it seems not working.
$("input[name*='ptype'][amount!='0']").each(function() {
$("input[name*='ptype'] , [amount!='0']").each(function() {
What am I missing ?
You can do it with && sign. Code depends on where your amount field is located and what it is. If I guess right it should be something like this:
$("input[name*='ptype']").each(function() {
if ($(this).val() == "" && $(this).parent().find(input[name='amount']).val() != 0) {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
That code $("input[name*='ptype'][amount!='0']").each(function() { is valid. You have to check the CSS selectors list.
The problem maybe in your *= selection. input[name*="ptype"] means Selects every element whose name attribute value contains the substring "ptype".
$('input[name*="ptype"][amount!="0"]').each(function() {
if ($(this).val() == "") {
$(this).css({'background-color' : '#feffe3'});
e.preventDefault();
alert("Enter Value!");
}
});
Take a look at this test https://jsfiddle.net/xpvt214o/211871/
« where another field» is the key in question.
So you need a selector to check if a selected element is empty and another element is not zero.
Holà!
Logic problem here.
with $(selector) you can look up for some elements.
There is no AND / OR in selectors for many sets of matching element.
A selector is ONE set of matching elements.
No way this selector can check for an attribute value of another set.
So you have to know your markup and navigate a bit... And take care of variable types.
$("input[name*='ptype']").each(function() {
if ( parseInt( $(this).next("input").val() ) != 0) {
$(this).css({"background-color" : "red"});
alert("Enter Value!");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ptype: <input type="text" name="ptype"><br>
amount: <input type="text" name="amount" value="1">
You have to look for another element's value here, from my understanding. So you have to know what is that "other" element and the methods to use may vary a lot depending on your HTML...
You can use this function in your button.
function check(e){
var verror = false;
$("input[name*='ptype']").each(function(index, value) {
var amount = $($("input[name='amount[]']").get(index)).val();
var ptype = $(this).val();
if(ptype.length <= 0 && amount.length > 0 ){
verror = true;
$(this).focus();
return false;
}
});
if(verror){
e.preventDefault();
alert("Enter Value!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="1"> <br>
ptype: <input type="text" name="ptype[]">
amount: <input type="text" name="amount[]" value="2"> <br>
<button type="button" onclick="check(event)">Click</button>
</form>

Jquery Unfocus field if value equals

What I am trying to achieve in the below code is when "0" has been entered into the input field it gets unfocused and other stuff triggers.
$(".val-0").keyup(function() {
if ($(this).val() === 0) {
$(this).blur();
// Do other Stuffss
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="val-0" type="number">
You are missing an opening quotation on the class name, for one thing.
For another, you are using === to compare which requires same data type (strict comparison). input.val() returns data of type string not integer.
Deeper explanation here.
You want to compare using $(this).val() == 0) or $(this).val() === '0')
$(".val-0").keyup(function() {
if ($(this).val() == 0) {
$(this).blur();
// Do other Stuffss
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input class="val-0" type="number">
Due to some reason you cannot attached keyup event to input type of number. I tried to put working example here. I hope it will help you.
$(".val-0").keyup(function(event) {
console.log(event.which + ", " + $(this).val());
if ($(this).val() === 0) {
$(this).blur();
console.log($(this));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="val-0" type="text" />

Adding a class name to number input when input has value

I'm using pure JS to try to add a class to a number input when the input has a value. The first part of the JS (which adds the "checked" state) is working, but the portion that adds the class name ("selected") isn't being applied. Any ideas what I'm doing wrong?
This is a combined radio and number input, hence the extra input type.
function select_radio_item_other_button(text_obj, radio_but)
{
if (document.getElementById)
{
el = document.getElementById(radio_but);
if (el.checked)
return;
if (text_obj.value != '')
el.checked = true;
text_obj.className += " selected";
}
}
And the HTML
<div class="other">
<input type="radio" name="radio_21" id="radio_21_22" checked="checked">
<label for="radio_21_22" id="radio_21_22_amt">
<input type="number" style="padding-left:0;" name="radio_21_22_amt" id="radio_21_22_amt" value="" min="0" max="50000000" step="1" onblur="javascript:select_radio_item_other_button(this, 'radio_21_22')">
</label>
</div>
Thanks all - I used a combination of your responses but this is working:
function select_radio_item_other_button(text_obj, radio_but)
{
var el = document.getElementById(radio_but);
if (text_obj.value != '') {
el.checked = true;
text_obj.className += " selected";
}
}
Brackets are a little off, perhaps something like this,
function select_radio_item_other_button(text_obj, radio_but) {
if (document.getElementById) {
el = document.getElementById(radio_but);
if (el.checked) {
return;
}
if (text_obj.value != '') {
el.checked = true;
text_obj.className += " selected";
}
}
}
Also not sure what if (document.getElementById) is supposed to return but what were you trying to accomplish here? It evaluates to true but that seems like an unintended purpose!
Hope this helps!

Jquery / window.onbeforeload in custom jquery function

I want to add to this code a "window.onbeforeload" event to show a message that prevent the user from quitting the current page without adding the products to cart.
I have to show only when the quantity in > than 0 and with respecting the code below.
How can I do that ?
<form> <p><input class="qty"
type="text" maxlength="1" value="0" /></p>
<p><input class="qty" name="text"
type="text" value="0" /></p> <p><input
class="qty" name="text2" type="text"
/></p> </form>
<script type="text/javascript">
$(".qty").change(function(e) {
if(this.value != '3' && this.value != '6' && this.value != '9') {
this.value = 0;
alert('You can buy only 3, 6, or 9 pieces fromn this product');
} }); </script>
Thanks for help :)
Not sure why everyone is suggesting globals. This method requires no globals and no change() listener (which you may still need if you want that alert there). Based on MDC, assuming support for [].indexOf:
window.onbeforeunload = function (e) {
var e = e || window.event;
if (['3','6','9'].indexOf($(".qty").val())>=0) {
return;
}
else {
var msg = 'You can buy only 3, 6, or 9 pieces from this product';
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = msg;
}
// For Safari
return msg;
}
};
With multiple inputs you will need to change the condition slightly:
var valid = true;
$('.qty').each(function(){ valid = valid && ['3','6','9'].indexOf($(this).val())>=0; });
if (valid) {
return;
}
else { ... }
You would need to set some "global" variable. GLobal does not necessarily mean global to the window, just enough it's global in your own namespace (which you hopefully got).
if(this.value != '3' && this.value != '6' && this.value != '9') {
NotifyTheUser = true;
}
else {
NotifyTheUser = false;
}
window.onbeforeunload = function() {
if( NotifyTheUser ) {
return 'Check your input.. foo bar yay!';
}
};
you can save the value in some global variable and then onbeforeunload look for that value, whether it's greater than 0 or not.
var valueContainer = 0;
$(".qty").change(function(e) {
valueContainer = this.value;
//rest of your code
});
window.onbeforeunload = function() {
if( valueContainer == 0) {
return 'Please Don't go away without selecting any product :(';
} };

Using JQuery to get the default value of a textarea, clearing onfocus and reinstating value on empty

I have some JQuery that isn't working and I need a little help. I a few forms on my website, and they all have a textarea with the class ".form-textarea". What I'm trying to do is use JQuery to get the default value of the textarea, clear the value on focus and reinstate the original value if the the textarea is empty. I realise that an ID would probably be better but I need a generic function to affect all of the textareas with this particular class.
$(document).ready(function()
{
var def = $(".form-textarea")
$(".form-textarea").focus(function(srcc)
{
if ($(this).val() == def)
{
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function()
{
if ($(this).val() == "")
{
$(this).addClass("defaultTextActive");
$(this).val(def);
}
});
$(".defaultText").blur();
});
This is an old method I used for the exact same purpose. I believe this is what you're looking for (uses Textareas) : Live demo
This uses the jQuery data API. I've also added an extra class so you can markup your text nicely (disabled_text). This is a general purpose method so all you need to do is add the suggest class to your textarea/input and the script will do the rest
<textarea class='suggest'>Some default value</textarea>
<textarea class='suggest'>Some default value2</textarea>
<textarea class='suggest'>Some default value3</textarea>
<input type='text' value ='me too' class='suggest'>
$('.suggest').each(function() {
$this = $(this);
if ($this.val() != '') {
return;
}
$this.data('defaultval', $this.val());
$this.addClass('disabled_text').focus(function() {
if ($this.val() == $this.data('defaultval')) {
$this.val('');
}
$this.removeClass('disabled_text');
}).blur(function() {
var oldVal = ($this.data('defaultval')) ? $this.data('defaultval') : '';
if ($this.val() == '' && oldVal != '') {
$this.addClass('disabled_text').val(oldVal);
}
})
});
Here, give this a whirl and see if it does the trick.
<script>
$(document).ready(function(){
$default = "defaultText";
$(".form-textarea").focus(function(){
if( $(this).val() == $default ){
$(this).removeClass("defaultTextActive");
$(this).val("");
}
});
$(".form-textarea").blur(function(){
if( $(this).val() == "" ){
$(this).addClass("defaultTextActive");
$(this).val($default);
}
});
});
</script>
<input class="form-textarea" type="text" value="defaultText" />
<input class="form-textarea" type="text" value="defaultText" />
I've just tried to remove the value "srcc" from the focus function and it works fine

Categories