Add an onclick function to existing HTML code with DOM [duplicate] - javascript

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 4 years ago.
My task is to inject a custom JS function to an HTML code where we cannot edit buttons and HTML it self, just inject some custom HTML code through GUI. What I have in the code:
<input class="ContinueAsAGuest LinkButton" name="submitForm" type="submit" value="Continue as a guest >" />
What I need:
<input class="ContinueAsAGuest LinkButton" name="submitForm" type="submit" value="Continue as a guest >" onclick = "captureOutcome()" />
I wanted to use DOM, but I failed, I stay get the original code. This what I have:
var guest = getElementsByClassName("ContinueAsAGuest LinkButton");
guest.onclick = "captureOutcome()";
function captureOutcome(
{'eventName':'event registration','eventAction':'start' }
);
I am guessing what I miss is to add the actual onclick to the original code.
Am I on the right path?

You need to use document.getElementsByClassName to get the element with that class name and if that is a unique class then use [0] to get the reference of that element. By getting the reference you can associate a click function into it.
var guest = document.getElementsByClassName("ContinueAsAGuest LinkButton")[0];
guest.onclick = captureOutcome;
function captureOutcome(){
alert('clicked!');
};
<input class="ContinueAsAGuest LinkButton" name="submitForm" type="submit" value="Continue as a guest >" />

Related

How to add class in input type text using Javascript? [duplicate]

This question already has answers here:
What do querySelectorAll and getElementsBy* methods return?
(12 answers)
Closed 1 year ago.
I want to add a class with input tags Because there is a problem with my display (it not beautiful) And I have to Add this class by using javascript and my code is as follows But it doesn't work I'm not sure where I went wrong.
mychoices.html
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.classList.addClass("browser-default");
});
</script>
myform.html
<div class="section">
<form action='.' method='POST'>
{% csrf_token %} {{ form.media }}
{{ form }}
<input type='submit' value='Save' class="button" />
</form>
</div>
Which I added classes browser-default and other existing classes must work correctly.
What should I do?
Thanks
So you're really close.
The first thing to note is that document.querySelectorAll returns a NodeList (like an array of elements). So you'll need to use forEach to loop over each input.
From MDN
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.
The second thing is that the classList.addClass doesn't exist. It's just classList.add. For more about Element.classList, please refer to this MDN article: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
Try the following instead:
<script>
document.addEventListener('DOMContentLoaded', function() {
new Choices('#choices-remove-button', {
removeItemButton: true,
});
var inputs = document.querySelectorAll('input[type=text]');
inputs.forEach(function (input) {
input.classList.add("browser-default");
})
});
</script>
X/Y problem "there is a problem with my display" - explain the problem instead of trying to fix a solution that might not be efficient or good practice. Also what is Choices ?
To answer your immediate question:
You are trying to add a class to a node list. That is jQuery syntax.
In vanilla JS, you need to use classList.add to each
document.querySelectorAll('input[type=text]').forEach(input => ;
input.classList.add("browser-default"));
or similar loop

calc is not defined at HTMLbutton.onclick [duplicate]

This question already has answers here:
Why does this simple JSFiddle not work? [duplicate]
(8 answers)
Closed 3 years ago.
I am beginner to JS and receiving error on this code.
I could not make it work and getting this error:
calc is not defined at HTMLButtonElement.onclick
Searching different stackoverflow questions and other sources online
<form>
Value 1: <input type="text" id="value1"> Value 2: <input type="text" id="value2">
<br/> Operator:
<select id="operator">
<option value="add">Add</option>
</select>
<button type="button" onclick="calc()">Calculate</button>
</form>
<input type="text" id="result"/>
JS Code:
function calc(){
var n1 = parseInt(document.getElementById('value1').value);
var v2 = parseInt(document.getElementById('value2').value);
var op = document.getElementById('operator').value;
if(op === 'add'){
document.getElementById('result').value = n1+n2;
}
I am getting the error I shared above in console.
JSFiddle
You're getting that error because the calc function is not defined when the HTML is rendered, therefore the onclick instruction can't point to it. Later on, when the user clicks on the button, the JavaScript engine notices that you're trying to execute an undefined function and throws an error.
You can solve this by registering the event listener after you define the function in your script, for example with this line (though things would be much better if the button also had an id):
document.getElementsByTagName("button")[0].addEventListener("click", calc);
For reference, see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

What is the difference between .getAttribute("name") and .name? [duplicate]

This question already has answers here:
getAttribute() versus Element object properties?
(7 answers)
Closed 5 years ago.
I have a simple web-application with an input text field in it looking like this:
<input id="txtip" type="text" value="10.1.1.50" />
The address 10.1.1.50 is a default value for an ip address. And from javascript I would read it like this:
txtip.getAttribute("value")
Now let's suppose to change it to 10.1.1.49. In google chrome the above javascript code will still return 10.1.1.50, while the expression
txtip.value
returns 10.1.1.49.
What is the difference? What is the "right way"?
var el = document.getElementById('testBox');
$(document).focusout(function () {
alert('el.value = ' + el.value);
alert('el.getAttribute("value") = ' + el.getAttribute('value'));
e.preventDefault();
});
<h2>Change value in the text box</h2>
<input id="testBox" type="text" value="original value" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Found this on web might help you try following code type something and focusout
The difference is that element.value is real time and if a user changes let's say, a textbox input, it will reflect that, and show you the new value.
While getAttribute('value') will still show the original value="whateverWasHere" value.

For onclick, when to use `onclick="confirmOnSubmit()` vs `onclick="confirmOnSubmit` [duplicate]

This question already has answers here:
what's the difference between <a onclick="someFunction"> and <a onclick="someFunction()">
(3 answers)
Closed 6 years ago.
I'm very new to HTML and JavaScript. I have seen onclick been assigned to function with following parentheses onclick="confirmOnSubmit() and functions without following parentheses onclick="confirmOnSubmit.
I was just wondering what is the difference between the two? When should I use one over the other?
<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>
using parentheses after a function name means invoking that function.However, using it without a parentheses just means the function itself.
<input type="submit" value="Submit" id="submitID" onclick="confirmOnSubmit()"/>
so in your example, it is basically saying that whenever the submit btn is clicked, invoke the confirmOnSubmit function.
<input type="submit" value="Submit" id="submitID"/>
document.getElementById('submitID').onclick=confirmOnSubmit
however, in the above example, we don't want to call the function at that moment, we just want to assign a reference, so that it can be called later on when the event happens.
hope it helps.

Get custom property from a button using Javascript [duplicate]

This question already has an answer here:
Select option base on property key in value
(1 answer)
Closed 6 years ago.
I have this button in HTML , with a property defined by me on it (data-filter-params):
<button class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button>
How can I take with JavaScript\JQuery the value for data-filter-params
plain javascript
var btn = document.getElementsByClassName('button')[0];
console.log(btn.dataset.filterParams)
jQuery
console.log($('.button').data('filter-params'));
This should solve it
var value
$(function(){
value = $('button').attr('data-filter-params')
})
JSfiddle: https://jsfiddle.net/mayank_shubham/3k97gg9k/
It's very easy,
HTML:
<button id="btnSubmit" class="button" type="submit" data-filter-params="{'Type', 'Filter.Type'},{'Code','Filter.Code'}" >Filter</button>
jQuery:
var attr = $('#btnSubmit').attr('data-filter-params');
alert(attr)

Categories

Resources