I have simple from which consists by inputs like that:
<form id='some-form'>
....
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
....
</form>
I'm trying to loop through this form and get data values:
$('#some-form').filter(':input').each(function (i, element) {
console.log(element.value);
console.log(element.attr('data-value'));
}
element.value holds value 'on' or 'off' depending radio is chosen or not and it works properly but when I try to call element.attr('data-value') it throws an error.
So how can I extract data-value in this loop?
use .children() instead of .filter().
The former will get you the elements inside the form, the latter will filter all elements $('#some-form') will provide.
HIH
EDIT
as pointed out by gaetanoM and connexo, there is also the issue of using element.attr() without the $() which you will need since .attr() is a method of jQuery, not JS
$('#some-form').children(':input').each(function (i, element) {
console.log(element.value);
console.log($(element).attr('data-value'));
//
// or
//
// console.log(element.dataset.value);
})
console.log('end');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
</form>
if you use newer jQuery >= 1.4.3
You can use like this.
$(this).data("value");
OR
$(this).data().value;
Inside your .each() function element is a regular HTMLElement, not a jQuery object.
Either wrap that using $(element) (or even $(this)) which allows to use
jQuery's $.attr()
$(element).attr('data-value')
or, even better, use the corresponding native DOM Api method
element.getAttribute('data-value'))
Since you are accessing a data- attribute, the DOM Api has a special object dataset to access these (from IE 11 upwards):
element.dataset.value
In case you have a name for your data-attribute like data-cmon-lets-go you can access it using camelcase notation:
element.dataset.cmonLetsGo
This could also be done with vanilla javascript.
document.querySelectorAll('#some-form input[type="radio"]').forEach(radio => {
console.log(radio.value, radio.dataset.value);
});
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">
</form>
In the each loop you are actually in the context of the radio element so you can use $(this).attr('data-value') and it will work. The following is a working code.
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form id='some-form'>
<input type="radio" data-type="4" data-value="25" data-id="68" name="req-68">Hello
</form>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$('#some-form :input').each(function (i, element) {
console.log(i);
console.log("element", element);
console.log($(this).val());
console.log($(this).attr('data-value'));
});
});
</script>
Related
I know this question has been asked -and answered- multiple times. However I found a new solution - but do not fully understand it. The setup is this:
<input id="input1" onchange="GetText()"/>
All answers i found suggest to use the id to get the value of the input.
function GetText(){
alert($("#input1").val());
}
$(this).val() does not work here.
Another way to use the value of the #input1 would be to use this.value in the calling function:
<input id="input1" onchange="GetText(this.value)" />
This passes the value as a parameter to the function.
However I found a JQuery sample that attaches a function to #input1 and makes $(this).val() work.
$("#input1").change(function(e){
alert($(this).val())
});
Against all answers here at stackoverflow seeing that it is possible to attach a function to a input field and have access to the value of it - I ask myself how I would have to write this function and not attach it with JQuery. Or can it be only attached with JQuery? Why?
Here is a fidle with this setup to play
You either pass reference to input object as a parameter in inline call to callback like this:
<input id="input2" onchange="GetText(this)" />
and then in javascript:
function GetText(_this){
alert(_this.value);
}
Fiddle here
Or you can attach function directly to input object like so
document.getElementById('input2').getText = function() {
alert(this.value);
};
and in html:
<input id="input2" onchange="this.getText()" />
Fiddle here
Basically this object in javascript is bound to context, in which the function has been created. When you define function globally, like GetText in your example, this is bound to global object in scope of that function.
<input id="input1" onchange="GetText.call(this)"/>
or
<input id="input1" onchange="GetText.apply(this)"/>
Will call the GetText function with the input as the value of this. Then you can use $(this) or this.value within the scope of GetText.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
If you're looking for a similar Vanilla JS function that you can put into you're HTML, which I actually don't recommend, because I support JavaScript HTML separation, it would be something like:
function getInputVal(context){
alert(context.value);
}
In your HTML:
<input id='whoCares' name='whoCares' value='Some Value' onchange='getInputVal(this)' />
Inline JS is not easy to maintain, especially if there's so much of it. It is better to separate your JS and HTML.
//Wait for DOM to load
$(function() {
//set up change event listener --> anonymous function
$('#input1').on('change', function() {
alert( this.value );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="input1" />
Or if you want to use a named function:
//wait for DOM to load
$(function() {
//Define function
function GetText(){
alert( this.value );
}
//set up change event listener --> named function
$('#input1').on('change', GetText);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="input1" />
All answers i found suggest to use the id to get the value of the input.
That's actually a pretty bad design; you want to create event handlers that can be unaware of the elements they're attached to.
The example without using jQuery would look like this:
var input = document.getElementById('input1');
input.addEventListener('change', function(event) {
alert(this.value);
}, false);
<input id="input1" />
See also: addEventListener()
I want to get the default value of an input textbox when the page was loaded. As I searched around I saw that the DefaultValue() is a method to get a value from a textbox when is loaded . But what is the jQuery one?
<input id=text > </input>
<script>
$(#text).DefaultValue(); // This is wrong I need the Jquery function of this
</script>
Any Idea?
You can read the defaultValue DOM property like this:
$('#text').prop('defaultValue')
Heres a working example
$('#value').click(function(){
alert($('#text').val())
});
$('#def').click(function(){
alert($('#text').prop("defaultValue"))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" value="This is the default value">
<button id="value">Click to see the current value</button>
<button id="def">Click to see the default value</button>
If you want to call a Javascript DOM function on a jQuery object, you can simple extract the corresponding DOM object with .get(0) or [0]:
$("#text").get(0).defaultValue;
$("#text")[0].defaultValue;
Note also that you were calling the basic JS wrong. First, it's defaultValue, not DefaultValue. Second, it's a property, not a method, so there's no parentheses after it.
Try this,
$(function(){
console.log($('#text')[0].defaultValue);
// or try
console.log($('#text').prop( 'defaultValue' ));
});
Read https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement
I have the following HTML:
<input class="file_upload" type="file" multiple="true" data-photoShootId="#item.PhotoShootItemId" />
And the following jQuery:
<script type="text/javascript">
$(function() {
$('.file_upload').uploadifive({
//*snip*
'formData': {
'PhotoShootItemId': $(this).data('photoShootId')
},
//*snip*
});
});
</script>
The script itself functions with no issues.
My problem is I cannot seem to get the data-photoShootId value from the file_upload element. I simply get undefined in my POST data. If I replace the .data call with a constant value, it works fine.
If I use $(this).attr and photoShootId="#item.PhotoShootItemId", I get the same result.
The issue is because this in your code does not refer to the element you are instatiating the plugin on, but the window.
To get an attribute from the element to use in the plugin call you need to loop over each individually:
$('.file_upload').each(function() {
$(this).uploadifive({
//*snip*
'formData': {
'PhotoShootItemId': $(this).data('photoShootId')
},
//*snip*
});
});
Please set the data attribute like this :-
<input class="file_upload" type="file" multiple="true" data-photoshootid="#item.PhotoShootItemId" />
And get the attribute like this
$(this).data('photoshootid')
Avoid using uppercase letters for data attributes
I'm using this code to set the HTML textbox value using Javascript function. But it seems to be not working. Can anyone point out, what is wrong with this code?
Whats your Name?
<input id="name" value="" />
<script type="text/javascript">
function setValue(value){
var myValue=value;
document.getElementsById("name").value = myValue;
}
</script>
the "value" is came from my android java class using this codes
String value = "Isiah";
WebView web = (WebView) findViewById(R.id.web1);
web.getSettings().setJavaScriptEnabled(true);
web.loadUrl("file:///android_asset/www/webpage");
web.loadUrl("javascript:setValue("+ value +")");
function setValue(value) {
var myValue=value; //unnecessary
document.getElementById("name").value= myValue;
}
But then as pointed out in the comments, you need to call setValue(value) somewhere in your code. Right now you just defined the function is never called.
You could either access the element’s value by its name:
document.getElementsByName("textbox1"); // returns a list of elements with name="textbox1"
document.getElementsByName("textbox1")[0] // returns the first element in DOM with name="textbox1"
So:
input name="buttonExecute" onclick="execute(document.getElementsByName('textbox1')[0].value)" type="button" value="Execute" />
Or you assign an ID to the element that then identifies it and you can access it with getElementById:
<input name="textbox1" id="textbox1" type="text" />
<input name="buttonExecute" onclick="execute(document.getElementById('textbox1').value)" type="button" value="Execute" />
You are using document.getElementsById("name") it should be document.getElementById("name")
not Elements it is Element
You are not linking the function to anything. For example, a click:
<input id="name" value="" onclick="javascript:this.value=12;"/>
Replace the onclick attribute for your desired function, whatever it does (you need to be more specific)
Also, there is no language attribute (at least not anymore) use type="text/javascript" instead
Here is a fiddle: http://jsfiddle.net/4juEp/
Click the input to see it working.
Look at this second fiddle. http://jsfiddle.net/4juEp/1/
which loads whatever is defined in the hid input to the name input.
Firstly, you have a typo in your javascript function i.e. you have used getElementsById as compared to getElementById
To set the value of the textbox on page load, I suggest you use an alternative
<body onload="setValue('yourValueToSet');">
<!-- Your usual html code in the html file -->
</body>
I think you are missing the quotes,
try,
web.loadUrl("javascript:setValue('"+ value +"')");
also consider about the typo.
Check this out:
<body onload="setvalue($value);">
Whats your Name?<input id="name" name="name" value=""/>
<script type="text/javascript">
function setValue(value){
document.{formname}.name.value = value;}</script>
It's not Elements
It's Element
You should use document.getElementById('object-id');
I have an odd problem.
I have button, "NextButton" that i want to hide initially but then when a checkbox is clicked, it should appear.
Below code doesn't work and it doesn't give any error. I've tested it on IE9 and FireFox 13
I searched other questions but couldn't find the problem that i am having...
<html>
<head>
<script language="javascript">
function enableNext() {
alert("clicked");
var s1 = document.getElementsByName("NextButton");
s1.style.visibility = "visible";
}
</script>
</head>
<body>
<input type="submit" name="NextButton" value="Next" style="visibility:hidden;"/>
<input type="checkbox" onClick="enableNext()" />
</body>
</html>
An array is returned in your code and you are applying style to an array. Change it to the code below.
function enableNext() {
alert("clicked");
var s1 = document.getElementsByName("NextButton")[0];//Get the first and only button in your case
s1.style.visibility = "visible";
}
document.getElementsByName returns an array of matched elements, you have to loop over it and change the style of individual items in the array. You can use jQuery to handle it easily $("[name='NextButton']").css("visibility", "visible") or if you want to use css display property you can use $("[name='NextButton']").show() or .hide(). Additionally if you don't want to use jQuery you can just use an id and instead of using getElementsByName use getElementById, it will return a single element that you need.
You should use id in HTML element and then document.getElementById(). This will give exact matched element.
<script language="javascript">
function enableNext() {
alert("clicked");
var s1 = document.getElementById("NextButton");
s1.style.visibility = "visible";
}
</script>
<input type="submit" id="NextButton" name="NextButton" value="Next" style="visibility:hidden;"/>
I guess you should try using css instead javascript alone.
Try using
document.getElementsByName("NextButton")[0];