JQuery onclick data attribute "undefined" - javascript

I am having an issue pulling the data attributes out of an input when using onclick="javascript()" syntax.
Here is a jsfiddle of what I am trying:
https://jsfiddle.net/123umaon/2/
<div>
<input onclick="Test();" type="button" value="test" data-section="thisSection"/>
</div>
function Test(){
var test = $(this).data('section');
alert(test);
}
I want to be able to pull the value of 'data-section' with the onclick action. But in my example it always comes back undefined.

You need to reference the current event. In the Test() function context, this refers to the window, instead of the DOM element.
$('#testOut').val("TEST TEST");
function Test(){
var test = $(event.currentTarget).data('section');
alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input onclick="Test();" type="button" value="test" data-section="thisSection"/>
</div>
Note: The window.event variable I'm using here is frowned upon on new code.

$('#testOut').val("TEST TEST");
function Test(selector){
var test = selector.data('section');
alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input onclick="Test($(this));" type="button" value="test" data-section="thisSection"/>
</div>

function Test(btn){
var test = $(btn).attr("data-section");
alert(test);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input onclick="Test(this);" type="button" value="test" data-section="thisSection" />
</div>
The problem is with your selector. "$(this)" in your example returns a reference to the function Test. Instead pass in this to the function and select off of the passed value.
Also, I would use the jQuery attr() funtion to set and return values on a custom property.

Your function passes in the "Window" object, you'd need to refine what you're passing through.
For getting the data-section attribute, you can use the .getAttribute() method on the element. It works similarly to .setAttribute().
https://www.w3schools.com/jsref/met_element_getattribute.asp

Related

jQuery attach onclick function to element

I have four image buttons with onclick events attached to them two pairs of two. I'm trying to replace those image buttons with text buttons and reattach the onclick function to the next text buttons. These buttons are not always on the page and I'm confined to using jQuery 1.4 otherwise .prop would make this a lot easier.
Consider this HTML:
<input type="image" src="path/to/image.gif" class="one" onclick="function()" />
<input type="image" src="path/to/image.gif" class="one" onclick="function()" />
<input type="image" src="path/to/image2.gif" class="two" onclick="function()" />
<input type="image" src="path/to/image2.gif" class="two" onclick="function()" />
I wrote the following jQuery code to get the onclick function, the inputs and rebind the onclick function.
$('input.one').each(function(){
var oneOnClick = $(this).attr('onclick');
$(this).replaceWith('<input type="button" value="one" class="one" onclick="'+oneOnClick+'" />');
)};
And the same for .two. I found out that the way the value of the onclick attribute is returned in jQuery means this cannot be done.
Using some resources online I updated my code to look like this:
var oneOnClick = $('input.one').first().attr('onclick');
var twoOnClick = $('input.two').first().attr('onclick');
$('input.one').each(function(){
$(this).replaceWith('<input type="button" class="one" value="one"/>');
});
$('input.two').each(function(){
$(this).replaceWith('<input type="button" class="two" value="two"/>');
});
$('input.one').live("click", oneOnClick);
$('input.two').live("click", twoOnClick);
But I'm getting an error
TypeError: undefined is not an object (evaluating 'b.split')
when input.one doesn't exist.
How can I make this work?
Please try the following code to bind onClick event
$(document).ready(function(){
$('input.one').each(function(){
$(this).attr('type',"button");
});
});
Well I suggest you to go with your first opted method:
Check this DEMO
function clickOne()
{
alert('hi');
}
function clickTwo()
{
alert('helleo');
}
$(document).ready(function(){
var oneOnClick = $('input.one').first().get(0).attributes.onclick.nodeValue;
var twoOnClick = $('input.two').first().get(0).attributes.onclick.nodeValue;
$('input.one').each(function(){
$(this).replaceWith('<input type="button" value="one" class="one" onclick="'+oneOnClick+'" />');
});
$('input.two').each(function(){
$(this).replaceWith('<input type="button" value="two" class="two" onclick="'+twoOnClick+'" />');
});
$('input.one').live("click", oneOnClick);
$('input.two').live("click", twoOnClick);
});
POINT TO NOTE:
$('input.one').attr('onclick') or $('input.two').attr('onclick') holds the value of the onclick attribute (which is a string). However, because the browsers treat the event attributes in a different way, they are
returned with function onclick() { clickOne() } and you know
about this. Thus, if you want to directly call the function, you'll
have to either strip the
function() {} or call it immediately or get it using
get(0).attributes.onclick.nodeValue
wrap clickOne and clickTwo in head and remaining things on document.ready

How can I get the id of a button?

I want to get the #id of an html button, so that I can use it elsewhere.
HTML
<input type="button" onclick="recordToFilename(this);"
id="submitdis" value="Enter Discount Price">
JavaScript
var x = document.getElementById("submitdis");
function recordToFilename(ele) {
console.log(ele.id);
}
Here's my codepen. My goal is to do something similar to this fiddle, but I'm not really sure where to start.
Try this vanilla JS:
var id;
function getId(button){
id = button.id
document.getElementById('output').innerHTML = id;
}
<input type="button" id="button1" onclick="getId(this)" value="Print my ID below.">
<p id="output"></p>
You don't need to get the element by id since you're already passing this in your onclick you have access to it in the function. if you just need the id you can get it by calling getAttribute on the element. Below is an example.
function recordToFilename(el) {
console.log(el.getAttribute('id'));
}
<input type="button" onclick="recordToFilename(this);" id="submitdis" value="Enter Discount Price" />
First you would need to import Jquery inside your html head tag,
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Then inside your js document this would be your code
$(document).ready(function() {
$('#buttonID').myNewFunc()
}
Let's suppose that on the DOM we have something like this :
<button id="submitdis" class="some-class" >Some Text</button>
to get the id on native JS :
var el = document.getElementById('submitdis');
console.log(el.id) // ===> OUTPUTS 'submitdis'
is that what you're looking for ?`

Hide div when input has an assigned value

I'm trying to hide a div when the value = 10
Here is the code and demo working fine:
<script>
$('input[name=test]').keyup(function(){
if($(this).val()<10)
$('#yeah').show();
else
$('#yeah').hide();
});
</script>
<label>Type whatever</label>
<input type="text" name="test"value="10" />
<div id="yeah" style="display:none;">
<input type="submit" />
</div>
But I'm trying to convert that code into Prototype code and I tried this code:
Event.observe(window, 'load', function () {
$('input[name=test]').keyup(function(){
if($(this).val()<10)
$('#yeah').show();
else
$('#yeah').hide();
});
});
I only want to hide the div when input value = 10 into prototype code.
Please somebody can help me?
Give the textbox an ID. For example:
<input type="text" id="txtbox" name="test" value="10" />
Change:
<div id="yeah" style="display:inline;">
To:
<div id="yeah" style="display:none;">
You need to use the $$ function which returns an array.
Event.observe('txtbox', 'keyup', function () {
if ($$('input[name="test"]')[0].value < 10){
$$('#yeah')[0].show();
}
else{
$$('#yeah')[0].hide();
}
});
Note: You could also use .first() instead of [0]
JSFiddle
you have a issue with prototype lib,
the Event.observe function is never triggered, secondly, you seem to still using the jquery api
$().keyup()
and you only load the prototype function.
Now days people rarely uses prototype, people use jquery for dom and underscore/lodash for iterations.

Accessing the javascript code inside the html tags

I am new to "html" and "Javascript".
<p id="pid"></p>
<script>
abc="hello";
document.getElementById("pid").innerHTML=abc;
</script>
<input type="text"
value="<script>document.getElementById("pid").innerHTML</script>"/>
How the code gets executed in the above case.
Looks like you are trying to set a value of the input field to be equal to the content of the pid paragraph. In this case you should set value property of the HTMLInputElement. You can get a reference to it using getElementById (there are many ways to get this element object) which you already know how to use. For example:
<p id="pid"></p>
<input type="text" id="input" />
<script>
var abc = "hello";
var pid = document.getElementById("pid");
pid.innerHTML = abc;
document.getElementById("input").value = pid.innerHTML;
</script>
the content of the 'value' attribute is just text, the browser will not interpret the JS code.
You can use the DOM instead:
<p id="pid"></p>
<script>
abc="hello";
document.getElementById("pid").innerHTML=abc;
</script>
<input id = "myInput" type="text" value="" />
<script>
document.getElementById("myInput").value = abc;
//OR : document.getElementById("myInput").value = getElementById("pid").innerHTML;
</script>
see : Accesing the javascript variable in html tag
I think you're trying to do this:
<script>
function myFunction(){
var abc="hello";
document.getElementById("pid").innerHTML=abc;
}
</script>
<p id="pid"></p>
<input type="button" value="Click Me" onclick="myFunction();" >

Error when trying to refer to a field by name

I am getting an error (document.my_formm.fieldName.value is null or not an object) from the below code:
<html>
<head>
<title>(Type a title for your page here)</title>
<script language=JavaScript>
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document.my_formm.fieldName.value);
}
</script>
</head>
<body>
<form name=my_form method=post>
<input type="text" onChange=check_length("my_form","my_text"); name=my_text rows=4 cols=30 value="">
<br>
<input size=1 value=50 name=text_num> Characters Left
</form>
</body>
</html>
Your check_length function is using variables to identify the form and field names, however, by using dot notation, you are referring to a element of document named my_formm. When you are are using variable names, you should use the bracket notation instead:
function check_length(my_formm,fieldName)
{
alert(fieldName);
alert(document[my_formm][fieldName].value);
}
Also, you should really quote attributes in your input:
<input type="text" onKeyPress="checkCompanyName();" onChange="check_length('my_form', 'my_text');" name="my_text" rows="4" cols="30" value="">
In your javascript you have referred to the form as 'my_formm' i.e. you have an extra 'm' at the end which is not present in the HTML, this could be your problem.
Why does your JavaScript method take in that first parameter if it never uses it?
Just do onChange=check_length(this)
and in your function
function check_length(element)
{
// element points to the element in question
// element.form points to the form if you need it
alert(element.value);
}
In general it would be nice to write WHAT error are you getting...
anyhow checkCompanyName is not defined in the code you wrote.
Also you're passing two strings as variable, they do not have properties...
A better way to do this:
<script type="text/javascript">
function checkLength()
{
inp = document.getElementById("myInput");
len = document.getElementById("len");
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength()" />
<input id="len" />
EDIT AFTER COMMENT:
<script type="text/javascript">
function checkLength(inputname, lenname)
{
inp = document.getElementById(inputname);
len = document.getElementById(lenname);
len.value = inp.value.length;
}
</script>
<input id="myInput" onkeyup="checkLength('myInput', 'len')" />
<input id="len" />
document.my_formm looks for a form named my_formm. You need to use the associative array sintax instead, like document[my_formm], which will pass the value in my_formm at runtime, rather than looking for a property in the document object called my_formm (which doesn't exist).

Categories