jQuery and val() undefined on ASP.NET using Visual Studio - javascript

I tried using this code to obtain the var value using jQuery. For some reason name equals null or undefined, and I can't seem to figure it out.
<asp:TextBox
ID="Text_Email"
runat="server"
CssClass=""
Width="234px">Email</asp:TextBox>
var name = $("#<%=Text_Email.ClientID%>").value; // name == undefined
Here is my main script:
$(document).ready(function () {
$("#<%=send_info.ClientID%>").click(function () {
// var name = document.getElementById("#<%=Text_Name.ClientID%>").value;
var name = $("#<%=Text_Email.ClientID%>").value;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if (reg.test(name) == false) {
$(this).val("");
$("#error_email_adress").removeClass('email_valid');
$("#error_email_adress").addClass('email_invalid');
return false;
} else {
$("#error_email_adress").removeClass('email_invalid');
$("#error_email_adress").addClass('email_valid');
alert("Message sent");
return true;
}
});
});
This part also confuses me. Why does this occur? Can someone explain to me why name is defined here?
$("#<%=Text_Email.ClientID%>").click(function () {
var name = this.value;//name != undefined;
});
whereas here name is undefined
var name = $("#<%=Text_Email.ClientID%>").value; // name == undefined;
Thank you for any help.

jQuery does not have value but val() function for textbox,
Try this,
var name = $("#<%=Text_Email.ClientID%>").val();
Your code will be
$("#<%=Text_Email.ClientID%>").click(function () {
var name = $(this).val();// you will get value in name by this statement.
});

Try this instead of what you've written
$(this).val()
Note that jquery's syntax is almost straightforward.The function concerning the value of an element is $.val() , you can set an element's value by passing it a string like :
$(this).val("the desired value");
or you can get the element's value by not passing it anything.

$("#<%=Text_Email.ClientID%>").click(function () {
var name = this.value; //<-- 'this' here is a DOM HTML Object which has .value property
var elem = jQuery(this); //<-- converts the DOM Object into a jQuery object, jQuery does not have .value property
var nameVal = elem.val(); //<-- get the value the jQuery way
});
Reading material:
jQuery .val()

Related

Uncaught ReferenceError: item is not defined

I am working on js validation and want to pass one function into another but i got error "Uncaught ReferenceError: item is not defined".
My code:
validation();
function validation() {
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,10})$/;
function common_inputs() {
var inputs = $(' input').toArray();
inputs.forEach(function(item) {
var element = $(item);
if (!element.val() == "") {
element.closest('.my__item').removeClass('error');
}
if ( !reg.test(element.val())) {
element.closest('.my__item').addClass('error');
}
})
}
function inputValidatorClick() {
common_inputs()
var element = $(item);
if (element.val() == "") {
element.closest('.my__item').addClass('error');
}
}
$('.my-button').click(inputValidatorClick)
$(' input').keyup(common_inputs)
}
},
It seems that there is problem with passing argument "item", but i am new in JS and have no idea how to solve it.
Does anyone knows how to solve it?
i would like to have it in one function - common_inputs. To not copy
the same part of code
I see that inside your inputValidatorClick function, you do something that is already inside common_inputs function.
Also, you can remove validation which is just used to wrap common_inputs function.
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,10})$/;
function common_inputs() {
$('input').each(function () {
$(this).closest('.my__item').removeClass('error');
});
$('input').filter(function () {
return this.value === '' || !reg.test(this.value);
}).each(function () {
$(this).closest('.my__item').addClass('error');
});
}
$('.my-button').click(common_inputs);
$('input').keyup(common_inputs)
First, we collect all of the <input> tags and remove all of the error classes from the parents (my__item).
Then, we filter the inputs which have invalid values (empty or not match with the regex pattern). From there, We add class error to the parents.

How to pass a value to javascript?

I'm working currently with Highcharts, I'm trying to create a function that use the data I write in a number field and present it as a new point in the chart once I click on add point, the add point showing in the link is to add point randomly to the chart.
http://jsfiddle.net/BlackLabel/2kw1b5o0/
<div id="container"></div>
<input type="number" id="add" name="new-point" value="">
<button id="add-point">Add point</button>
<script>
var chart = Highcharts.chart('container', {
series: [{
data: [1, 2, 3, 4, 5]
}]
});
function getValue(add) {
ext = document.getElementById(id).value; //value of the text input
alert(text);
return false;
}
var x= document.getElementsByClassName("new-point").value;
document.getElementById('add-point').addEventListener('click', function() {
chart.series[0].addPoint();
});
There were a few issues with your code :
Your getValue function needs the name of the field as a parameter and that parameter will be used in the document.getElementById() function to retrieve the fields you want to read data from
You need to return the read value by using the return keyword
Your chart expects a number. So, you need to parse read with Number.parseFloat()
Then, your event handler needs to call the getValue function and provided the name of the field :
function getValue(fieldName) {
let value = document.getElementById(fieldName).value; //value of the text input
return Number.parseFloat(value);
}
document.getElementById('add-point').addEventListener('click', function() {
let value = getValue("add");
chart.series[0].addPoint(value);
});
Updated JSFiddle
Just get the value of input as you are doing in getValue function. You can either return the value from that function like
function getValue() {
var val= document.getElementById("add").value,
return val;
}
and now you can use it like
document.getElementById('add-point').addEventListener('click', function() {
var val = getValue();
chart.series[0].addPoint(val);
});
Or you can directly access the value in you click handler as
var el = document.getElementById("add")
document.getElementById('add-point').addEventListener('click', function() {
chart.series[0].addPoint(el.value);
});
Here is your updated fiddle
document.getElementById(id).value returns a String value, and addPoint is expecting an Int, try this:
document.getElementById('add-point').addEventListener('click', function() {
var point = document.getElementById('add').value;
chart.series[0].addPoint(parseInt(point));
});
From HighChart's documentation, addPoint doesn't accept parameters of type String : https://api.highcharts.com/class-reference/Highcharts.Series#addPoint
Since the value of the input returns a String, you need to parse it to a float or a number :
function getValue(id) {
let inputValue = document.getElementById(id).value;
return parseFloat(inputValue);
}
Now you can call getValue in your EventListener :
chart.series[0].addPoint(getValue('add'));

Getting returned value from a callback function -JQuery

I'm new to jQuery and I know this is probably super easy. I wanna get the returned value from a callback function in an event. Code is here:
$('.hintItem').on('mouseenter', function(e){
changeItemStyle(e);
var hintItemIndex = $(this).index();
return hintItemIndex;
});
I want to grab the value of hintItemIndex and store it to a new variable. Could anyone kindly help me?
Try this:
var hintItemIndex;
$('.hintItem').on('mouseenter', function(e){
changeItemStyle(e);
hintItemIndex = $(this).index();
});
Basically, you define a variable outside the fuction and assign a value to it via the function.
Try following function.
function getHintItemIndex() {
var retVal;
$('.hintItem').on('mouseenter', function(e){
changeItemStyle(e);
var hintItemIndex = $(this).index();
return hintItemIndex;
});
return retval;
}
var retVal = getHintItemIndex();

How to get jQuery callback fire return value?

I have this problem getting the return value from jQuery.Callback(), below is my code.
This code generate using PHP:
var data = {text : "Invalid input value", callback : "foobar"}
Now using Javascript:
function foobar(text){
//Check if empty
return (text == '') ? true : false;
}
var callbacks = $.Callbacks();
callbacks.add(data.callback);
var response = callbacks.fire('Hell World');
// I need the return value here form foobar function
alert(response)
The code above return jQuery $.Callbacks() object and not boolean. Any ideas or alternative to jQuery.Callbacks() ? Thanks in advance.
As discussed the objective was to call a dynamic function whose name was stored in data.name so
var response = window[data.callback]('somethng')

jQuery 'if' statement not working

This should be a simple if statement, but it's not working for me. Essentially, when you click an element, I want that element to be highlighted and the ID to be put into a the variable value. However, if in the situation the same element is clicked twice, I want to value = NULL.
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
var value = $(this).attr('id');
} else {
value = NULL;
}
});
})(jQuery);
Your primary problem is that you're "hoisting" the value variable by redefining it with the var keyword. This code can also be written more efficiently with a lot less code. This should work:
(function($) {
// somewhere outside click handler
var value = '';
// click handler
$(".list").click(function() {
var id = $(this).toggleClass('hilite').attr('id');
value = (value === id) ? null : id;
/* or if you prefer an actual if/else...
if (value === id) {
value = null;
else {
value = id;
}
*/
});
})(jQuery);
Edit: a couple general comments about the original snippet that might be useful:
NULL should be null
Try not to run the same selector multiple times, or recreate a jQuery object from the same DOM object multiple times - it's much more efficient and maintainable to simply cache the result to a variable (e.g., var $this = $(this);)
Your comparison there is probably "safe", but better to use !== than != to avoid unintentional type coercion.
Not sure how exactly you intended to use value in the original example, but always remember that variables are function-scoped in JavaScript, so your var value statement is hoisting the value identifier for that entire function, which means your assignments have no effect on anything outside that click handler.
You need to declare var value outside the scope of the function, so that its value is maintained across function calls. As it is, the value variable is lost right after it is set, because it goes out of scope.
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = temp;
} else {
value = null;
}
});
})(jQuery);
You could do:
(function($){
var tmp = {};
$(".list").click(function() {
$(this).toggleClass("hilite");
var id = $(this).attr('id');
if (!tmp[id]) {
var value = id;
tmp[id] = true;
} else {
value = NULL;
tmp[id] = false;
}
});
})(jQuery);
In this way you use a tmp object that stores the state for all the different id's
It might not be skipping that statement, you might just be getting a confusion over the implied global "value" and the local "value".
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) { // <-----------------Implied global var called "value"
var value = $(this).attr('id'); // <---Local variable valled "value"
} else {
value = NULL; // <---------------------Which one am I
}
});
})(jQuery);
Also, it ought to be value = null as NULL is just an undefined variable.
This should be a working example of both points:
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = null;
}
});
})(jQuery);
Do you not need to declare value before you use it in the conditional statement?
you aren't setting a value in this function.
var value = "NULL";
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = "NULL";
}
});
})(jQuery);
The variable value is not defined. And it either needs to be a global variable or you could use jQuery's $('.selector).data() method to attach it to the element:
http://api.jquery.com/data/
I also recommend using !== for the comparison, since that compares the type of the variable as well as the content.

Categories