How can i get element id in js function? - javascript

JS doesn't see input ID(undefined). I have no idea why it doesn't work. I found many solutions in google, but it still doesn't work.
index.html :
<div ng-class="{'form-group has-success':checkValue(answer) == true,'form-group has-warning': checkValue(answer) == false}">
<input id="422"
maxlength="3"
type="Integer"
class="form-control"
style="width: 100px"
ng-model="answer"
ng-blue="checkValue(answer, id)">
</div>
$scope.checkValue = function(value, id) {
$scope.val = id;
console.log($scope.val);
if ($scope.val == value)
return true;
else
return false;
}
The console just shows:
undefined

with jquery:
(function($) {
$( document ).ready(function() {
var inputId = $('input').attr('id');
console.log(inputId)
});
})( jQuery );
with pure javascript:
var inputs = document.getElementsByTagName("input");
var inputId = inputs[i].id;
console.log(inputId);

You can get the ID by using the following code:
$('ELEMENT').attr('id');
You can also use this code for getting other attributes as class name etc.

You can get the ID by using the following code:
$('.form-control').attr('id');

You can get ID by following code:
var element_id = $("input[ng-model='answer']").attr("id"); //Here I am using other unique property of the element to get its attribute
You can also make use other property also or else you can make use of other Jquery selector like this
var element_id = $(".form-control").attr("id"); //This may give unexpected result if class name is repeated
or
var element_id = $("input.form-control").attr("id"); //This is more assuring way since, we are providing class name along with element name

Related

How can I get a specific variable reading the data atribute on element?

I have some fields on my site, and they are the same, but each one of then should update some jquery variable with it's value.
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
I need that depending on the data-atribute, they run the same function, but update the variable pointed in the atribute.
Example:
for = "0";
int = "0";
agi = "0";
$( "input" ).focusout(function() {
data-atribute-of-the-element = $(this).val;
})
I have no know idea how to do this.
And seems stupid to create a different function for every input.
Thanks in advance!
Create an object which has a field which is your variable. Something like below.
var a={'for':'0','int':'0','agi':'0'}
$( "input" ).focusout(function() {
a[$(this).attr('data-atribute')] = $(this).val();
console.log(a.for);
console.log(a.int);
console.log(a.agi);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
.attr() does work, but since you're using data attributes anyway, you may as well use the .data() function designed for them.
See comments in the code snippet for explanation:
/* Set up an object to contain the values you're capturing.
This means we won't have to predefine all the variables or
set them individually; it also means you can use reserved words
like "for", which wouldn't work as variables on their own: */
var capturedValues = {};
$( "input" ).focusout(function() {
// This gets the contents of the "data-atribute" attribute:
var theName = $(this).data("atribute");
// This captures the value of the current input field,
// and puts it in the capturedValues object using theName as the key:
capturedValues[theName] = $(this).val();
// Later on you can reference these as e.g. capturedValues.agi
// Show the results (just for demo):
console.log(capturedValues);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input data-atribute="for"></input>
<input data-atribute="int"></input>
<input data-atribute="agi"></input>
How about:
var for = "0";
var int = "0";
var agi = "0";
$( "input" ).focusout(function(s) {
switch ($(this).attr('data-attribute')) {
case 'for':
for = $(this).val();
break;
case 'int':
int = $(this).val();
break;
case 'agi':
agi = $(this).val();
break;
}
//OR
var t = $(this).attr('data-attribute');
if (t == 'for') for = $(this).val();
else if (t == 'int') int = $(this).val();
else if (t == 'agi') agi = $(this).val();
})
PS: 'atribute' has 2 t's : attribute
Use the .attr function of jQuery:
$( "input" ).focusout(function() {
let data-atribute-of-the-element = $(this).attr('data-atribute');
})

Jquery find all elements with custom attribute begin with, get rest of it's name and it's value

Let's say we have element with custom attribute
... bind-html="varName" ...
I want to find all elements with attribute beginning with "bind-",
then get second part of it's name, which is unknown, in this case "html".
And at last get it's value "varName".
How do i achieved this with Jquery? I don't want to use second attribute to describe attibute to bind (like .. bind="varName" attr="html" ..)
You can use a loop through each object's attributes this.attributes and use the attribute's name and value properties.
Running example:
$("input").each(function() {
$.each(this.attributes, function() {
if (this.name.indexOf('bind-') == 0) {
console.log(this.name + ' has the value: ' + this.value);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<input bind-koby='hello'>
<input bind-douek='stack'>
<input will-not-show='yes'>
<input bind-hello='overflow'>
well that what you are looking for like
<div bind-html="varName">hi there i am </div>
well hi thats me
var namer = $(" *[attr*='bind']").text();
console.log(namer);
<div class="bindable" data-bind="html:varName1"></div>
<div class="bindable" data-bind="css:varName2"></div>
<div class="bindable" data-bind="js:varName3"></div>
<div class="bindable" data-bind="whatEver:varName4"></div>
(function(){
let bindables = $('.bindable');
bindables.each(function(){
let bindData = $(this).data('bind');
let bindDataArray = bindData.split(":");
console.log(bindDataArray);
});
}());
now u will get array with data u want
You can get all elements and their attributes which contain bind- by using jquery .properties and .indexOf() like following example.
// $("*") selects all elements in your html
$("*").each(function() {
$.each(this.attributes, function() {
// checks whether element has an attribute starts with "bind-" or not
if(this.specified && this.name.indexOf("bind-") !== -1) {
console.log("Attr Name: "+ this.name + " Attr Value: " + this.value)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span bindNot-html="bindNot">element1</span>
<div bind-html="varName1">element2</div>
<a bind-html2="varName2">element3</a>
<div bind-html3="varName3">element4</div>
<span bindNot-html="bindNot">element5</span>

How to get multiple checkbox value and assign to hidden field

I want to store the multiple id to hidden field.
So value able to bind to controller.
<form:hidden id="ids" path="ids" value="${ids }"/>
When click button delete will call jquery to delete row.
var deleteIds = [];
$("#deleteRow").on('click', function() {
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
$('#ids').val(deleteIds);
});
My question is
How to set the value into ids?
Thank You.
The tag from doesn't have the attribute value. You can check the attributes for the form tag here.
However, you can use jQuery to modify custom attributes. Here's a working fiddle:
var deleteIds = [];
deleteIds = ["1","2","3","4"];
$('#ids').attr("value",deleteIds);
alert($('#ids').attr("value"));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ids" path="ids" value="${ids }"/>
By creating multiple <form:hidden/>, you can get what you want. I assume you when you click #deleteRow, table rows is deleted and you submit form of these ids to server, so we can make it by follow.
Cause I even don't know your html structure, so I've just tried to modify your script, may help you;)
var deleteIds = [];
$("#deleteRow").on('click', function() {
$('#ids').remove();
deleteIds = $('.case:checkbox:checked').val();
$('.case:checkbox:checked').parents("tr").remove();
for (var i = 0; i < deleteIds.length; i++) {
// formId should be replaced to your form id
$('#formId').append('<form:hidden id="ids" path="ids" value="' + deleteIds[i] +'"/>');
}
// $('#formId').submit(); comment this line, cause there is another button to submit form.
});
I able to set the multiples value to hidden field. Answer as below.
<form:hidden id="ids" path="ids" value="${ids }"/>
$("#deleteRow").on('click', function() {
var deleteIds = [];
$('.case:checkbox:checked').each(function(i){
if($('#ids').val() != ''){
deleteIds[i] = $('#ids').val() + "," + $(this).val();
}else{
deleteIds[i] = $(this).val();
}
});
$('#ids').attr("value",deleteIds);
});
The each(function(i)) will loop all the checkbox and store in array[], after that assign the array to hidden field.

exclude the first string from being appended to a character

FIDDLE Example
I'm learning how to append all the data attributes from div.query elements to a url string: http://web.com?get=
With the script I can get this result:
"http://web.com?get=|Africa|Asia|Europe"
But is there any way not to have the first one coupled with "|" so that the url should be
"http://web.com?get=Africa|Asia|Europe"
I want to get that result because either http://web.com?get=|Africa|Asia|Europe
or http://web.com?get=Africa|Asia|Europe| would be invalid. Any suggestions?
JS:
$( document ).ready(function() {
$(".query").each(function() {
var div_terms = $(this).data('term'),
source = $('#main').data('source');
var x = source+'|'+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
HTML:
<div id="main" data-source="http://web.com?get="></div>
<div class="query" data-term="Africa"></div>
<div class="query" data-term="Asia"></div>
<div class="query" data-term="Europe"></div>
<div class="result"></div>
The easiest way is to pull all the countries to an array and join them using the pipe character.
var terms = $('.query').map( function() {
return $(this).data('term');
}).get().join('|');
var source = $('#main').data('source');
$('.result').html( source + terms );
Demo
http://jsfiddle.net/cHtT6/3/
You just need to replace the first '|' in the resulting url with an empty character ''.
Make it simple use javascript join function
$( document ).ready(function() {
var terms=[];
$(".query").each(function() {
var div_terms = $(this).data('term');
terms.push(div_terms);
});
var x = $('#main').data('source')+terms.join("|");
$('.result').html(x);
});
Fiddle here
Use an if statement to check if it's the first 'data-term'. If it is then don't use the | character. Then in the else statement you just do as you've already done
DEMO
Just Check whether end is reached like this:
$( document ).ready(function() {
var i=0;
$(".query").each(function() {
i++;
var div_terms = i==$(".query").length? $(this).data('term')+"":$(this).data('term')+"|",
source = $('#main').data('source');
var x = source+''+div_terms;
$('#main').data('source',x);
$('.result').html(x);
});
});
Here when last term is reached. Automatically only "" is appended in all other cases "|" is appended.

How to Select hidden input tag with name in b/w the form tag in jquery/javascript

I want to select the hidden box with jquery.
What i did.
In a web page number of forms exists. I want to select the individual form and its in b/w hidden box with jquery. my Javascript code is:
function replace_val(clickval)
{
var id = $(clickval).attr('id');
var valuer = $(clickval).attr('value');
var formid = $("statictext"+id).val();
$('input[type=hidden][name="packagesale"]').val(valuer);
$('input[type=hidden][name="pre_post"]').val('Postpaid');
alert(formid >'input[type=hidden][name="packagesale"]').val());
}
My HTML Code where this function call.
<input style="width:85px;" class="btn btn-danger" onClick="replace_val(this);" type="button" id="<?php echo $sno;?>" value="<?php echo $value;"/>
I think something is wrong in my alert box code....
Your selector is wrong inside the alert(). You should use:
function replace_val(clickval)
{
var id = $(clickval).attr('id'),
valuer = $(clickval).attr('value'),
formid = $("#statictext"+id);
$('input[type=hidden][name="packagesale"]').val(valuer);
$('input[type=hidden][name="pre_post"]').val('Postpaid');
alert(formid.children('input[type="hidden"][name="packagesale"]').val());
}
you also have error on line
var formid = $("statictext"+id).val();
will be
var formid = $("#statictext"+id).val();
//or
var formid = $(".statictext"+id).val();// if using class
Don't over use jQuery if possible try in pure javascript only
var id = clickval.id;
var valuer = clickval.value;

Categories

Resources