please help me with this code
this i a javascript code
not the actuall
var elements, searchText = "Open Help";
elements = YAHOO.util.Dom.getElementsBy(function (element) {
return (element.innerHTML === searchText) ? true : false;
}, "a", document);
if (elements.length > 0) {
//do something with elements[0]
}```
you are using get method on your form.Replace that with POST method
Your question is confusing and vague and I have no idea what you're trying to do, but with the input text you can just change the url with this:
window.location.href
Related
For example, I have
<div class="welcome_font">name</div>
and
<div id="nameho" style="color:#5AC7E6;">another-name</div>
I want to write an "if" statement in jquery/javascript where if "name" matches "another-name", then do something. How do I do that?
The .html() function grabs the inner html when using jQuery. So you could use the following to compare the two:
if ( $('.welcome_font a').first().html() === $('#nameho').html() )
{
...
}
let me know if that makes sense or if you have any questions :)
Try,
if( $('.welcome_font a').text() == $('#nameho').text() )
{
////Do something
}
Research first next time. You could get this with a simple search.
if($(".welcome_font a").text() == $("#nameho").text())
{
//To do
}
var name_1 = $('.welcome_font').text();
var name_2 = $('#nameho').text();
if(name_1===name_2) {
alert('yes');
} else {
alert('no');
}
Demo : http://jsfiddle.net/TSGqC/
or
var name_check = ($('.welcome_font').text()===$('#nameho').text()?true:false);
if(name_check) {
alert('yes');
}
Demo : http://jsfiddle.net/TSGqC/1/
In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});
I'm trying to call a function only if an HTML element is empty, using jQuery.
Something like this:
if (isEmpty($('#element'))) {
// do something
}
if ($('#element').is(':empty')){
//do something
}
for more info see http://api.jquery.com/is/ and http://api.jquery.com/empty-selector/
EDIT:
As some have pointed, the browser interpretation of an empty element can vary. If you would like to ignore invisible elements such as spaces and line breaks and make the implementation more consistent you can create a function (or just use the code inside of it).
function isEmpty( el ){
return !$.trim(el.html())
}
if (isEmpty($('#element'))) {
// do something
}
You can also make it into a jQuery plugin, but you get the idea.
I found this to be the only reliable way (since Chrome & FF consider whitespaces and linebreaks as elements):
if($.trim($("selector").html())=='')
White space and line breaks are the main issues with using :empty selector. Careful, in CSS the :empty pseudo class behaves the same way. I like this method:
if ($someElement.children().length == 0){
someAction();
}
!elt.hasChildNodes()
Yes, I know, this is not jQuery, so you could use this:
!$(elt)[0].hasChildNodes()
Happy now?
jQuery.fn.doSomething = function() {
//return something with 'this'
};
$('selector:empty').doSomething();
If by "empty", you mean with no HTML content,
if($('#element').html() == "") {
//call function
}
In resume, there are many options to find out if an element is empty:
1- Using html:
if (!$.trim($('p#element').html())) {
// paragraph with id="element" is empty, your code goes here
}
2- Using text:
if (!$.trim($('p#element').text())) {
// paragraph with id="element" is empty, your code goes here
}
3- Using is(':empty'):
if ($('p#element').is(':empty')) {
// paragraph with id="element" is empty, your code goes here
}
4- Using length
if (!$('p#element').length){
// paragraph with id="element" is empty, your code goes here
}
In addiction if you are trying to find out if an input element is empty you can use val:
if (!$.trim($('input#element').val())) {
// input with id="element" is empty, your code goes here
}
Empty as in contains no text?
if (!$('#element').text().length) {
...
}
Another option that should require less "work" for the browser than html() or children():
function isEmpty( el ){
return !el.has('*').length;
}
You can try:
if($('selector').html().toString().replace(/ /g,'') == "") {
//code here
}
*Replace white spaces, just incase ;)
document.getElementById("id").innerHTML == "" || null
or
$("element").html() == "" || null
Vanilla javascript solution:
if(document.querySelector('#element:empty')) {
//element is empty
}
Keep in mind whitespaces will affect empty, but comments do not. For more info check MDN about empty pseudo-class.
if($("#element").html() === "")
{
}
Are you looking for jQuery.isEmptyObject() ?
http://api.jquery.com/jquery.isemptyobject/
Here's a jQuery filter based on https://stackoverflow.com/a/6813294/698289
$.extend($.expr[':'], {
trimmedEmpty: function(el) {
return !$.trim($(el).html());
}
});
JavaScript
var el= document.querySelector('body');
console.log(el);
console.log('Empty : '+ isEmptyTag(el));
console.log('Having Children : '+ hasChildren(el));
function isEmptyTag(tag) {
return (tag.innerHTML.trim() === '') ? true : false ;
}
function hasChildren(tag) {
//return (tag.childElementCount !== 0) ? true : false ; // Not For IE
//return (tag.childNodes.length !== 0) ? true : false ; // Including Comments
return (tag.children.length !== 0) ? true : false ; // Only Elements
}
try using any of this!
document.getElementsByTagName('div')[0];
document.getElementsByClassName('topbar')[0];
document.querySelectorAll('div')[0];
document.querySelector('div'); // gets the first element.
Try this:
if (!$('#el').html()) {
...
}
Line breaks are considered as content to elements in FF.
<div>
</div>
<div></div>
Ex:
$("div:empty").text("Empty").css('background', '#ff0000');
In IE both divs are considered empty, in FF an Chrome only the last one is empty.
You can use the solution provided by #qwertymk
if(!/[\S]/.test($('#element').html())) { // for one element
alert('empty');
}
or
$('.elements').each(function(){ // for many elements
if(!/[\S]/.test($(this).html())) {
// is empty
}
})
I hope this isn't a daft question. I expected google to be promising but I failed today.
I have a textbox <input type="text" id="input1" /> that I only want to accept the input /^\d+(\.\d{1,2})?$/. I want to bind something to the keydown event and ignore invalid keys but charCode isn't robust enough. Is there a good jQuery plugin that does this?
The affect I want to achieve is for some one to type 'hello world! 12.345' and want all characters to be ignored except '12.34' and the textbox to read '12.34'. Hope this is clear.
Thanks.
I don't think you need a plugin to do this; you could easily attach an event and write a simple callback to do it yourself like so:
$('#input1').keyup(function()
{
// If this.value hits a match with your regex, replace the current
// value with a sanitized value
});
try this:
$('#input1').change(function(){
if($(this).data('prevText') == undefined){
$(this).data('prevText', '');
}
if(!isNaN($(this).val())){
$(this).val($(this).data('prevText'))
}
else {
//now do your regex to check the number settings
$(this).data('prevText', $(this).val());
}
})
the isNAN function checks to make sure the value is a number
$('#input1').bind('keyup', function() {
var val = $(this).val();
if(!val)
return;
var match = val.match(/^\d+(\.\d{1,2})?$/);
if(!match)
return;
//replace the value of the box, or do whatever you want to do with it
$(this).val(match[0]);
});
jQuery Keyfilter
Usage:
$('#ggg').keyfilter(/[\dA-F]/);
It also supports some pre-made filters that you can assign as a css class.
You should look at jQuery validation. You can define your own checking methods like this here.
$('input1').keyup(function(){
var val = $(this).val().match(/\d+([.]\d{1,2})?/);
val = val == null || val.length == 0 ? "" : val[0];
$(this).val(val);
});
I found the solution.
Cache the last valid input on keydown event
Rollback to last valid input on keyup event if invalid input detected
Thus:
var cache = {};
$(function() {
$("input[regex]").bind("keydown", function() {
var regex = new RegExp($(this).attr("regex"));
if (regex.test($(this).val())) {
cache[$(this).attr("id")] = $(this).val();
}
});
$("input[regex]").bind("keyup", function() {
var regex = new RegExp($(this).attr("regex"));
if (!regex.test($(this).val())) {
$(this).val(cache[$(this).attr("id")]);
}
});
});
I'm trying to pick out the value of an input box using jquery.
No probs there
$('#id_of_my_input_box_1').val();
But I need several so decided to put them into a loop:
============
var config_total_instances = '==some value='
for (var x = 1; x <= config_total_instances; x++) {
if (isset($('#id_of_my_input_box_'+x).val())) {
alert($('#id_of_my_input_box_'+x).val());
}
}
============
If I submit the form and I've got say 10 input boxes, the code above doesn't alert a value if the relevant input box has value.
I'm using a function below to check for values.
============
function isset(my_variable) {
if (my_variable == null || my_variable == '' || my_variable == undefined)
return false;
else
return true;
}
============
Am I missing something vital..? :-(
Addition: I shoudl add that I'm askign why I don't get the value of
$('#id_of_my_input_box_'+x).val()
echoed out in my alert box
Extending #Faber75's answer. You can set a class name for all your text element and then use something like this
$("input:text.clsname").each(function(){
if (isset(this.value)) {
alert(this.value);
}
});
In your current code if you are assigning a string to config_total_instances then it will not work.
don't consider my message an answer, more of a tip.
For a simplier code you could consider adding a class to the textboxes you need to check.
For example adding to all the inputs you need to check the class="sample" you could the use the jquery selector $(".sample") , returning you all the items and then you could simply do
$(".sample").length to count the items and $(".sample")[0].val() (or similar) to get/test values.
Cheers
Have you tried this? (note that there are three =)
if (my_variable === null || my_variable == '' || my_variable === undefined)
As an alternative to this try
if (typeof(my_variable) == 'null' || my_variable == '' || typeof(my_variable) == 'undefined')
Maybe I'm misunderstanding, but can't you just get all the <input>'s in a <form> that aren't :empty if that's the end goal of what you're trying to accomplish?
$('form#some_id input:not(:empty)').each(function () {
// do something with $(this).val() now that you have
// all the non-empty <input> boxes?
});
Or if you're just trying to tell if the user left some <input> blank, something like:
$('form#some_id').submit(function (e) {
if ($(this).find('input[type="radio"]:not(:checked), input[type="text"][value=""], select:not(:selected), textarea:empty').length > 0) {
e.preventDefault(); // stops the form from posting, do whatever else you want
}
});
http://api.jquery.com/category/selectors/form-selectors/