Syntax error - how to get value of textbox - javascript

I have a trouble getting value from text box. Conventional javascript getElementByName returns error :undefined. I was able to use jQuery in other examples with select. But can't find a reference anywhere about input tags. This line shows syntax error:
var total = = $('input[name='+formQty+'] :text').val();
What is a jquery for picking value/text of a textbox?

you have 2 equal signs.
var total = $('input[name='+formQty+'] :text').val();
It might be easier also to stick an ID attribute on the input tag and use this
var total = $('#myInputId').val();
make sure you are calling it from a loaded dom:
$(function() {
var total = $('#myInputId').val();
});

From what I understand your query selector is incorrect.
It should be 'input[name='+formQty+']:text' the :text as you have it is trying to select any text elements underneath the current input resulting in nothing. You can even get rid of the :text and only select the element based on name. .val() should then work if you have properly selected the input element.
You should also debug this by just performing the $('...') method without the function call and see what elements are returned.

Regarding your problem getting this to work with getElementByName() - that's probably because the method is actually getElementsByName() - note the plural elementS. It returns a list of all elements with the specified name, accessible via array syntax; even if there is only one matching element you still get a list (with only one thing in it).
If you are sure there will be exactly one element with the specified name you can do this:
var elementValue = document.getElementsByName(name)[0].value;

Related

HTML input field returns blank despite having value

It's really strange and puzzling me why is it returning blank despite having value. Am I missing something silly?
you can use this code to test if there any duplicate Ids on your DOM
$('[id]').each(function(){
var ids = $('[id="'+this.id+'"]');
if(ids.length>1 && ids[0]==this)
console.warn('Duplicate ID: #'+this.id);
});
The selector for Jquery ID only take the first occurrence.

textContent returns undefined

I have a table in which I want to extract the text of the active item. I do this with the following code:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
console.log(addedWorkout);
addedWorkout = addedWorkout.textContent;
console.log(addedWorkout);
The problem is that I keep getting undefined. I checked the console and it indeed finds the element I want without fail.
I am relatively new to Javascript, but after over an hour of Googling I could not find the issue and I don't understand why. I know that I can get the text element if I hardcore it using the following line:
document.querySelector("#selectiona1").textContent
but not with:
$("#selectiona1").textContent
What is the difference between these 2? I read that textContent is part of the DOM, to my understanding it relates to objects and according to my console i think it is an object. I made some crazy attempts like putting the object I got into the querySelector, but nothing works.
With this line:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active");
you're using jQuery to select the .dropdown-item.active inside #custDropDownMenuA, and when you select with jQuery, you get a jQuery object in response. So, addedWorkout is a jQuery object, and jQuery objects generally do not have the same properties/methods as standard HTMLElements. (querySelector is the vanilla Javascript method to retrieve an element)
Either select the [0]th item in the jQuery collection to get to the first matching element:
var addedWorkout = $("#custDropDownMenuA").find(".dropdown-item.active")[0];
Or use the jQuery method to get the text of the first matching element, which is .text():
var addedWorkoutText = addedWorkout.text();
(note the use of a new variable - you will likely find it easier to read and debug code when you create new variables rather than reassigning old ones, when possible)
Your var 'addedWorkout' is a Jquery object, not a html element.
To show the text use:
addedWorkout.text();
Alternatively, you can change the 'addedWorkout' to a html element by adding the index [0], like this:
addedWorkout[0].textContent;

Get the ID of an element where the class contains a given string

I am currently trying to figure out a way to get the ID of an element, depending on whether its class contains something. I'm not sure if there's a better way to do it than I currently am, but having looked around nothing fits exactly the need I have. The code I currently have is, where I am looking for a div element whose class contains the string "one" but is not limited to that. Currently there is only one element containing this string but the alert provides me with [Object NodeList] (I may well be overcomplicating this):
$idToMove = document.querySelectorAll('div[class^="one"]');
alert($idToMove);
document.querySelectorAll() Returns a node list (kind of like an array), if you are sure there will only ever be one you have a couple options.
1) Use .querySelector instead:
// returns the first node that matches
var elm = document.querySelector('div[class~="one"]');
console.log(elm.id);
2) Access the first element in the returned list:
// returns all nodes that match
var elms = document.querySelectorAll('div[class~="one"]');
console.log(elms[0].id);
Make sure to null check returns of .querySelector and length check returns of .querySelectorAll.
Notice also, that I use ~= and not ^=. You can read on the MDN about the difference between all the equality operators. But for these two:
[attr~=value]
Represents an element with an attribute name of attr whose value is a whitespace-separated list of words, one of which is exactly "value".
[attr^=value]
Represents an element with an attribute name of attr and whose first value is prefixed by "value".
First get element from DOM and than from that element get id attribute:
1- If you need only first element then use querySelector like this:
let elms = document.querySelector('div[class~="one"]')[0].id
console.log(elms)
2- If you need all element those have this class then use querySelectorAll like this:
let elms = document.querySelectorAll('div[class~="one"]')
for(let i=0; i<elms.length; i++)
{
console.log(elms[i].id)
}
I think with "*" it works in more cases
document.querySelector('div[class*="words"]')
i tried it works absolutely amazing
window.frames[0].document.querySelector('td[id*="sss"]')

Default Value in drop down list not being selected

I have a drop down list [ Incident, Question, Problem, Task]. I have written a code when an end user logins in and has a tag called product the default value should be problem. However it does not seem to work. It still gives the user the option to select values from the list.
$j(document).ready(function() {
if(location.pathname == '/requests/new') {
var ct = currentUser.tags;
if(ct.indexOf("product") >= 0){
$j(document.getElementById("ticket_fields_75389").value = "Problem");
}
else {
$j(document.getElementById("ticket_fields_75389").value = "");
}
}
})
Note: This answer is incorrect. I will delete it once I know the OP read my comment.
It still gives the user the option to select values from the list.
Well, of course, setting value will only change the initially selected value. If you want "fix" the value of the select element, so that the user cannot change it, you have to make it read-only. Lets stick with jQuery (what you have is a weird mix of DOM API and jQuery †):
$j("#ticket_fields_75389").val("Problem").prop('readonly', true);
†: Let's have a close look at the line
$j(document.getElementById("ticket_fields_75389").value = "Problem");
What exactly is happening here? Obviously we have a function call ($j(...)) and we pass something to it. This "something" is the result of the expression
document.getElementById("ticket_fields_75389").value = "Problem"
This finds an element by ID and assigns the string "Problem" to the value property. This is an assignment expression. The result of an assignment expression is the assigned value, i.e. "Problem".
That is the value that is passed to $j(...), so we have $j("Problem");. Since $j refers to jQuery, this would search for all elements with tag name Problem, which does not exist in HTML. It would also return a jQuery object, but you are not doing anything with it.
Hence the wrapping in $j(...) is completely unnecessary or even wrong, even though it doesn't throw a syntax or runtime error.

live function with out arguments in jQuery

I wanna select some item by jQuery which has been added after loading page,so I wanna use live() function.I used it before for clicking like following code:
$("selector").live('click')
but now when I wanna use it in another function.
but It will not work with out argument,like it live()
for e.g followin code will alert test (work)
var pos_eq=Math.abs($('.myList').css("left").replace("px","")/$('.myList').children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
but this will not.
var pos_eq=Math.abs($('.myList').live().css("left").replace("px","")/$('.myList').live().children('li').eq(0).css('width').replace("px","")) + 1;
alert("test");
how can I solve it?
You want a function, not a variable. It looks like you are trying to keep pos_eq up to date after elements have been added to the page. Having a variable auto-update when the DOM changes in the way you are trying to do is not possible with JavaScript. What you can do is use a function instead of a variable. This way whenever the value is accessed you are getting the latest value because it is computed on demand:
function pos_eq() {
var list = $('.myList');
var left = parseInt(list.css("left"));
var width = parseInt(list.children('li').eq(0).css('width'));
return Math.abs(left / width) + 1;
}
I broke your code up into multiple statements to make it more readable. You would use this function the same as you used the variable, but instead add parens to the end to invoke the function:
alert(pos_eq);
alert(pos_eq());
To get a set of objects at the time you need them, just do $("selector"). That will do a query at that time and get the set of objects. There is no need to use .live() in order to query objects on the page. It does not matter whether the objects were part of the original page or were added dynamically later. When you do $("selector"), it will search the contents of the current page and get you the objects that are currently in the page that match the selector.
There is no way to do a live selector query and save it and have it automatically update in jQuery or any other library I know of. The way you solve that issue with a dynamic page is that you just do a new query when you need current results.
The description of live() is: Attach a handler to the event for all elements which match the current selector, now and in the future. It does not give you a live node list despite its name. jQuery does not have any method that returns a live node list(such as those returned by getElementsByTagName etc.) as far as I know.

Categories

Resources