I am trying to select one input box, But because i may have more than one inputs, i am trying to limit the one i am selecting. Here is my jquery code that select the the input but for some reason it doesn't work. Is theresomething i am doing wrong? This is be executed once the document is ready.
if ( $("input[name='RETURN.URL'][value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']").length > 0 )
{
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}
Here the html
<input type="hidden" name="RETURN.URL" value="http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST">
<input type="hidden" name="SUBMIT_OPTIONS" value="">
Your selector is using the HTML escaped attribute value:
[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']
The actual value of the selector should use & and not &:
[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']
The value was HTML escaped so that the value would be correctly represented within the attribute, but the query selector needs to match by the actual value.
You'd probably be better off using a simple selector such as a class. This is particularly important, as the URL represented in the [value] attribute could have its query string parameters in any order and represent the same resource.
HTML entities are translated before they're shown in the browser, therefor & becomes & and so forth. So when you're filtering the selector you're looking for something that's been translated into something else.
Here's the JSFiddle.
Without getting into details of why you're selecting input elements this way, you just need to understand what I said and change the selector to:
$("input[name='RETURN.URL'][value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']")
use jQuery attr() method
if($("input[value='http://link.com?TYPE=P&PID=ST-L09F166&CONSTITUENCY=WBST']").attr('name') == 'RETURN.URL'){
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}
Unless otherwise, these contents are dynamically added, it is better to give this input an id, and access via it.
lose the dot in RETURN.URL (its not a preferred way of adding names with dots to input elements)
& use $('input[name=RETURNURL]').val().length
Check the value instead of using it as a selector.
JSFiddle
if ( $("input[name='RETURN.URL']").val().length > 0 )
{
alert("Transcript report");
}
else
{
alert("Not Transcript Report");
}
Related
HELP!!.... I can't dynamically access data entered by users into Input fields!
I'm a curriculum-designer trying to make a 'Matching'-activity (18-questions-with-18-scrambled-up-possible-answers), in which answer-choices get dynamically crossed out, 1 by 1, as they get 'used up' by the student, whenever (s)he types the letter of that choice (in this case "r") into the input-field. Here's the HTML for 1 of those 18 matches: (Hint: Pay attention to the "id"-attributes)
HTML
<input title="Question 18 - type 'R' into this input field"
class="questions" maxlength="1" id="18" onblur="My_Blur_Fx(this);">
</input>
<span class="r_as_selected, choices" id="r"> <!--I use the first class ('r_as_selected') in the J-Query example below, and the 2nd class ('choices') in the Javascript example below.-->
[Choice] R. (**All this span should soon be crossed-out.**)
</span>
I thought I could pull this off with a "change" event. However, neither my Javascript, nor my J-Query seems to be able to do it, because neither one can dynamically access the user's typed-in input (the very stuff that PHP would normally access via GET or POST).
J-Query
My J-Query-attempt to dynamically access this user-entered input...
$("input").change(function(){
$("input"[value="r"])
.add('.r_as_selected')
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'})
});
...failed because, although it could cross out the '#r' answer-choice, yet it would ALSO cross it out whenever they typed in ANYTHING....So the [value='r'] part of the code wasn't able to target JUST the field where someone had typed 'r'.
Javascript
My Javascript-attempt to dynamically access this user-entered input...
<script>
function My_Blur_Fx(x) {
var userInput = document.getElementById(x).value;
var userChoices = document.getElementsByClassName("choices").id;
var i;
for(i = 0; i < 18; i++)
{ if (userChoices[i].attributes[1].value == userInput) {
/*Note: "attributes[1] is my way of accessing the 2nd attribute in the HTML span above, which is 'id="r"'*/
userChoices[i].style.textDecoration = "line-through";};
};
}
</script>
...failed too because an 'Input' is an "Element" whose "Value," is defined by the DOM to be "NULL,"...so line 3 above gives an error. Neither could any of the other potentially-relevant DOM-modifiers, instead of .value (i.e. .innerHTML / .nodeValue / .attributes) access that user-entered value. So it seems that 'Input' elements just can't be accessed dynamically. . . . ( Any suggestions...J-Query, Javascript, or other? )
You can't use an attribute selector to match user input, it only matches the static attributes, not the dynamic values. You can use .filter() to search for an element that matches a selector and has a specific value.
$("input").change(function() {
$("input").filter(function() {
return this.value == 'r';
}).add(".r_as_selected")
.eq(1).css({'color': 'red', 'text-decoration': 'line-through'});
});
You have several problems in MyBlurFx().
document.getElementById(x).value won't work beceause x is the element, not its ID. You should just use x.value.
document.getElementsByClassName("choices").id won't work because getElementsByClassName() returns a NodeList, not a single element, so it doesn't have an id property. But you don't need the ID, just use document.getElementsByClassName("choices"), since the for loop operates on the elements, not IDs.
Maybe there is more than one mistake, but I see that your code $("input"[value="r"]) is same as $(undefined). You must use $('input[value=\'r\']') instead.
I'm having some trouble understanding how to use nested selectors in jQuery. I'm parsing a list of classes from my university and I want it to let me know if a class I want is open. However, the website doesn't use css AT ALL, so the only way of identifying the class I want is open is to read the color attribute of the font tag.
Here's the block of HTML I'm trying to read
<TD><FONT FACE='Arial' SIZE='-1' COLOR='Black'>nameOfClass</TD>
Here's how am I'm trying to read it, and display an alert if the font tag attribute color of nameOfClass is "Black", which means its open. It's nasty but its the only way I can tell if the class is available or not.
function main() {
$(document).ready(function(){
if $("td").text()=="nameOfClass"
if $(this "font").attr("COLOR")=="Black" {
alert("It actually works!");
}
});
I never get an alert when I run this though. I'm pretty sure its my syntax, it's been a long while since I did any sort of coding so I might be making some stupid mistake.
You can use .children. But in order for your code to work, you have to iterate over all td elements, not just compare the text value of the first one:
$("td").each(function() {
if($(this).text() === 'nameOfClass' &&
$(this).children('font').attr('color') === 'Black') {
alert("It actually works!");
}
});
Otherwise, $("td").text()=="nameOfClass" only tests whether the text of the first td element in the page is "nameOfClass", which is certainly not what you want. You want to find all td element which contain that string.
You could do it much simpler if you'd directly select all font elements whose color attribute has the value "Black", with the attribute selector. Then you filter out the ones that don't contain the class name and count how many elements are left over. If none, then the class is not open.
var classIsOpen = $('font[color="Black"]').filter(function() {
return $(this).text() === 'nameOfClass';
}).length > 0;
You only need to do an exact comparison of the class name if it could occur as part of an other name, e.g. "Web" and "Advanced Web". If that's not the case, you can make the code even shorter, with the :contains selector:
var classIsOpen = $('font[color="Black"]:contains("nameOfClass")').length > 0;
I have implemented this function (libphonenumber javascript )in a website
http://www.phoneformat.com/
How do i get the value returned by this html tag. Whether Yes or No
< DIV id="phone_valid" class="popup-value"></DIV>'
I have tried this
function checkSubmit(){
var country=$("#phone_valid").val();
if(country=="No")
{
alert("Not a valid number");
return false;
}
So far no luck
The .val() method is primarily used to get the values of form elements such as input, select and textarea.
Use
$("#phone_valid").text();
to get DIV text content or
$("#phone_valid").html();
if you want markup.
First, no space between < and div (saw here: < DIV id="phone_valid" class="popup-value"></DIV>' )
Second:
function checkSubmit(){
var country=$("#phone_valid").text(); // it is a div not input to get val().
if(country=="No")
{
alert("Not a valid number");
return false;
}
You probably want to do this:
$("#phone_valid").html();
or
$("#phone_valid").text();
you can use this:
document.getElementById("phone_valid").innerHTML;
.val() is for form elements. You should use .text() or .html() to get the value from a DIV.
HTML
<DIV id="phone_valid" class="popup-value"></DIV>
JavaScript
function checkSubmit(){
var country=$("#phone_valid").html();
if(country=="No")
{
alert("Not a valid number");
return false;
}
}
Hope this helps!
In vanilla JavaScript you can use document.getElementById to get a specific node using ID:
var node = document.getElementById('phone_valid');
And then to get the text from that node you will need to use:
var text = node.innerText || node.textContent;
The jQuery .val() method is used on form fields like input, textarea, select...
If you need to include HTML comments then consider using contents() method
$('#mydiv').contents()
Other wise html() method or even text() will be what you are looking for because val() purpose is for form elements ;)
My javascript is
function changeImage(imgID) {
var baseurl = "media/images/";
if (document.getElementById(imgID).src == baseurl+"selection-off.png") {
alert('Success');
document.getElementById(imgID).src = baseurl+"selection-no.png"; }
else {
alert('Fail'); } }
and my HTML is
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage('mustard-img')" /></div>
I always get Fail when clicking the image. I must be missing something really elementary.
Some browsers convert the img src to the full url (including http://www....)
try alerting it to make sure..
You could use the
document.getElementById(imgID).src.indexOf( baseurl+"selection-off.png" ) >= 0
which checks if one string is contained in the other..
Alert string document.getElementById(imgID).src. It might be taking complete path i.e. including host name while the string you are comparing with has relative path.
I tried your code on my own server.
Result:
document.getElementById(mustard-img).src is
'http://localhost/webfiles/media/images/selection-off.png'
baseurl+"selection-off.png" is 'media/images/selection-off.png'
baseurl seems to show the relative url only.
So that is the reason why "Fail" gets alerted.
Try with the following code:
<div id="mustard" class="checkbox"><img id="mustard-img" class="no-off" src="media/images/selection-off.png" alt="checkbox" onClick="changeImage(this)" /></div>
<script>
function changeImage(img) {
if (img.src.indexOf('selection-off.png')) {
alert('Success');
img.src.replace(/selection-off.png/, 'selection-no.png');
}else{
alert('Fail');
}
}
</script>
The differences with your code:
passing the img reference: this instead of the id in the onclick function
use indexOf instead of ==, for relative paths
Are you sure the DOM is built when the script is loaded ?
It's because the src attribute is changed by the browser. Don't do it that way, the proper way to check and change the css class or style attribute instead.
Image-based checkboxes are quite common, but here is the full solution.
1) Render actual checkboxes first. These work for 100% of browsers.
2) When the page loads, place your "image checkbox" next to the checkbox and hide the checkbox
3) When the image is clicked, toggle the checkbox and use the hidden checkbox to ascertain the state of the image.
When the form is POST-ed, the checkboxes will act like normal checkboxes. If JavaScript is disabled or otherwise not available the form is still usable.
I'm having an impossibly hard time finding out to get the actual DOMElement from a jQuery selector.
Sample Code:
<input type="checkbox" id="bob" />
var checkbox = $("#bob").click(function() { //some code } )
and in another piece of code I'm trying to determine the checked value of the checkbox.
if ( checkbox.eq(0).SomeMethodToGetARealDomElement().checked )
//do something.
And please, I do not want to do:
if ( checkbox.eq(0).is(":checked"))
//do something
That gets me around the checkbox, but other times I've needed the real DOMElement.
You can access the raw DOM element with:
$("table").get(0);
or more simply:
$("table")[0];
There isn't actually a lot you need this for however (in my experience). Take your checkbox example:
$(":checkbox").click(function() {
if ($(this).is(":checked")) {
// do stuff
}
});
is more "jquery'ish" and (imho) more concise. What if you wanted to number them?
$(":checkbox").each(function(i, elem) {
$(elem).data("index", i);
});
$(":checkbox").click(function() {
if ($(this).is(":checked") && $(this).data("index") == 0) {
// do stuff
}
});
Some of these features also help mask differences in browsers too. Some attributes can be different. The classic example is AJAX calls. To do this properly in raw Javascript has about 7 fallback cases for XmlHttpRequest.
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
If you need to interact directly with the DOM element, why not just use document.getElementById since, if you are trying to interact with a specific element you will probably know the id, as assuming that the classname is on only one element or some other option tends to be risky.
But, I tend to agree with the others, that in most cases you should learn to do what you need using what jQuery gives you, as it is very flexible.
UPDATE: Based on a comment:
Here is a post with a nice explanation: http://www.mail-archive.com/jquery-en#googlegroups.com/msg04461.html
$(this).attr("checked") ? $(this).val() : 0
This will return the value if it's checked, or 0 if it's not.
$(this).val() is just reaching into the dom and getting the attribute "value" of the element, whether or not it's checked.