How to find input element id by value? - javascript

How do I get the id of an input element based on its value? The values will always be unique and there are only seven of them. I have tried this:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return this.id;
});
But nothing is returned!

Try
$(this).id nope, this.id works, no need to create a jQuery object for the ID.
or
$(this).attr('id')
HTH
EDIT:
This might work:
$('#wrapper').find("input[value='"+value+"']").attr('id');

You write return this.id;… Return where? You simply return value from anonymous functions and I don't see where you ever trying to use it. So the answer is:
var idYouAreSearchingFor = $('#wrapper').find("input[value='"+value+"']").attr('id');

your code is almost good:
$('#wrapper').find("input[value='"+value+"']").each(function(){
return $(this).attr("id")
});
check here
http://jsfiddle.net/5xsZt/
edit: i have just tested it with this.id it works to. Your code is right. Your error is somewhere else: check it:
http://jsfiddle.net/5xsZt/3/

You can solve this using a filter. Like this:
$('#wrapper input').filter(function() {
return $(this).val() == value;
}).each(function() {
return this.id;
});

Here's a version that will definitely work in all mainstream browsers:
function getInputWithValue(wrapper, value) {
var inputs = wrapper.getElementsByTagName("input");
var i = inputs.length;
while (i--) {
if (inputs[i].value === value) {
return inputs[i];
}
}
return null;
}
var wrapper = document.getElementById("wrapper");
var input = getInputWithValue(wrapper, "some value");
window.alert(input.id);

Related

Curious if angularJs has better method to calculate number of checkboxes

I need to check if any checkbox is checked. so i am doing it like
self.isButtonEnabled = function() {
var selectLineCheckboxs = document.getElementsByClassName('selectLineRadioInput'),
i = 0, checkboxLength = selectLineCheckboxs.length - 1;
for (i = 0; i <= checkboxLength; i++) {
if (selectLineCheckboxs[i].checked) {
self.selectLineChecked = true;
break;
} else {
self.selectLineChecked = false;
}
}
return self.selectLineChecked;
};
in return i get true if any checkbox is checked.
so quite simple,
Now here i am looking if we can do the same with angularJs with any better approach and i do not want to use watch() function in angular.
I can help with your some code to convert it to look like in Angular way.
use angular.element (provided by jQLite to get element) as instead of document.getElementsByClassName
You could use $filter while checking attribute is checked or not
CODE
self.isButtonEnabled = function() {
var selectLineCheckboxs = angular.element('.selectLineRadioInput');
var checkedValues = $filter('filter')(selectLineCheckboxs, { 'checked': true }); //do filtering and contains check value
self.selectLineChecked = checkedValues.length > 0 ? true : false;
return self.selectLineChecked;
};
Note: You should add $filter dependency on your controller before using $filter
Update
I'd suggest you to create your own custom filter that could be usable in multiple purposes, or dynamically check property value is true or not. I know your code is as same as you ask in answer, but I putted some of your code as reusable component, which can dynamically work for any property value to check is true or not.
Filter
.filter('isPropertyTrue', function () {
return function (elements, property) {
var returnArray = [];
angular.forEach(elements, function (val, index) {
if (val[property]) returnArray.push(val)
});
return returnArray;
}
});
Code
$scope.isButtonEnabled = function () {
var selectLineCheckboxs = document.getElementsByClassName('selectLineRadioInput');
var checkedValues = $filter('isPropertyTrue')(selectLineCheckboxs, 'checked');
self.selectLineChecked = checkedValues.length > 0 ? true : false;
return self.selectLineChecked;
};
JSFiddle
Hope this could help you, Thanks.
i have been using it this way with ng-bind variable in scope $scope.Items .and the binded variable can be used to see what all items are checked.
angular.forEach($scope.Items,function(key,value)
{
if(key.Selected)
{
counter++;
}
});
Here is a JSFiddle to illustrate the same

searching inputs for duplicated values except this

I'm in a medium project and a issue occurs.
I have extracted the essence of the problem to this fiddle
What this code is
$(".6").focusout(function(){
if( $(".6").filter(function(){ return this.value;}).not(this).length>0)
{ $(this).val("duplicated");}
What this code should do is get this.value and search it in other inputs, if it productive, alert the user and prevents the blur. The setback is in searching by value (if()), it does'nt working.
UPDATE
I have made a change in fiddle above: now the event sets a new value to input instead alert() and focus()
I have noticed that filters by "have a value" and not "have the value".
The main issue is regarding the filter.
.filter(function(){ return this.value;})
The jQuery filter method will return all jQuery objects where the return value is true. In the above code, every input that has a value will result to true.
To fix this, first save the value of the current input being modified, and then compare it with each value of the elements:
$(".6").focusout(function (e) {
var val = this.value;
if( $(".6").filter(function(){ return this.value === val;}).not(this).length>0){
$(this).val("duplicated");
}
})
A few additional tips. If you use the not() method first, then you will reduce the number of filter queries by 1.
$(".6").focusout(function (e) {
var val = this.value;
if( $(".6").not(this).filter(function(){ return this.value === val;}).length>0){
$(this).val("duplicated");
}
})
Even better, you can use the siblings() selector instead to only select other elements.
$(".6").focusout(function (e) {
var val = this.value;
if ($(this).siblings(".6").filter(function () { return this.value == val; }).length > 0) {
$(this).val("duplicated");
}
})
In this particular case, you can omit >0 in the if statement
$(".6").focusout(function (e) {
var val = this.value;
if ($(this).siblings(".6").filter(function () { return this.value == val; }).length) {
$(this).val("duplicated");
}
})
see: http://jsfiddle.net/tleish/VM2fy/4/

Get return value from given function using Jquery or Javascript

I have the Browser render source code in HTML following format.
There is button and on that button click one java-script function is called and I want the Return value from java script function.
Return value from that function.
Please refer below code for your reference,
Thanks,
Digambar K.
This is way to get return value using javascript:
function myFunction(value1,value2,value3)
{
}
var returnValue = myFunction("1",value2,value3);
if(returnValue.value1 && returnValue.value2)
{
//Do some stuff
}
This is way to get return value using jquery:
function getMachine(color, qty) {
var retval;
$("#getMachine li").each(function() {
var thisArray = $(this).text().split("~");
if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
retval = thisArray[3];
return false;
}
});
return retval;
}
Use:
OnClientClick="return //javascript code"
instead of
onclick
Try this:
var returnValue;
$(document).ready (function(){
var myButton = $("#yourbuttonsid");
var originalEventHandler = myButton[0].onclick;
myButton.click(function(e) {
returnValue = originalEventHandler();
});
});
//Here you can do anything with returnValue

How to echo something from javascript to div class html

Javascript
function validateForm() {
var result;
var keywords = document.querySelectorAll('#keywords');
[].slice.call(websites).forEach(function(website) {
if (website.value == '') {
website.focus();
HERE I SAY SOMEHOW THE ERROR
result = false;
return true;
}
});
return result;
}
HTML
<div class="error-website">HERE THE ERROR IS GETTING ECHOED</div>
How do i echo website in that div above and how do i add the error in that if condition.
Try:
document.querySelectorAll('.error-website')[0].innerHTML = 'Website';
As NULL and VisioN has pointed , this:
document.querySelector('.error-website').innerHTML = 'Website';
is even faster , because of "querySelector is faster unless the match is the last DomNode in the DOM".
First of all, it would be more appropriate to use an ID not a class; the reason is that classes are meant for, well, classes (i.e. categories) of elements; however, in your case, you are dealing with one single unique element (you'll only have one), so assuming you take my advice and change to the following markup:
<div id="error-website">HERE THE ERROR IS GETTING ECHOED</div>
... it will be as simple as:
document.getElementById('error-website').innerHTML = "whatever <strong>you</strong> <em>like</em>";
$(".error-website").text("Website")
document.getElementById('error-website').innerHTML = ....
if you use an id...
Use DOM document.getElementsByClassName
Eg.
function validateForm() {
var result;
var keywords = document.querySelectorAll('#keywords');
[].slice.call(websites).forEach(function(website) {
if (website.value == '') {
website.focus();
HERE I SAY SOMEHOW THE ERROR
result = false;
return true;
}
});
return result;
var a=validateForm();
if(a){
document.getElementsByClassName("error-website")[0].innerHTML=a;
}
NOTE: getElementsByClassName() does not work in Internet Explorer 5,6,7, and 8

jQuery, next, prev, cycling to first and last

Sorry for this confusing title.
What i'm trying to do is a function (or just a simple way), which will do simple .next(), but if there's no next element, match first. And the same for .prev() - if there's no previous element, match last.
So i made it this way:
var current_selected = getSelected();
if(current_selected.length) {
var prev = current_selected.prev();
if(prev.length) {
setSelected(prev);
return;
}
}
setSelected(getLast());
But i don't really like it, i think there's some pretty way do it. Any thoughts?
(getSelected and getLast returns jQuery objects.
You could create some little convenience plugins:
$.fn.nextWrap = function() {
var $next = this.next();
if ($next.length) return $next;
return this.siblings().first();
};
$.fn.prevWrap = function() {
var $prev = this.prev();
if ($prev.length) return $prev;
return this.siblings().last();
};
Then you can simply do $('#something').nextWrap() or $('#something').prevWrap().
Here's a quick demo: http://jsfiddle.net/qpDKL/
Note: This will behave mostly like prev() and next() (with the wrap behavior, of course), but it doesn't support the prev|next(selector) syntax.
Edit: Here's a slightly more terse plugin syntax since they're nearly the same anyway:
$.each(['next', 'prev'], function(i, nextOrPrev) {
$.fn[nextOrPrev + 'Wrap'] = function() {
var $item = this[nextOrPrev]();
if ($item.length) return $item;
return this.siblings()[nextOrPrev === 'next' ? 'first' : 'last']();
};
});
This will work for prev case
var current_selected = getSelected();
var prev = current_selected.prev();
if(prev.length) {
setSelected(prev);
} else {
setSelected(getLast());
}
The best way that I can think of would be to have an array of the elements that you want to cycle. You can cycle through an array in two ways:
array.push(array.shift());
or
var count = 0;
function cycle() {
return array[count++ % array.length];
}
I think the former looks cleaner.
http://jsfiddle.net/ExplosionPIlls/feeF5/
Something around these lines:
if (!$('selected').next().length)
return $('selected').parent().children().first();
else
return $('selected').next();
if (!$('selected').prev().length)
return $('selected').parent().children().last();
else
return $('selected').prev();

Categories

Resources