How to add a class without access to HTML - javascript

I want to add an additional class to an input. I have no access to the HTML to change the code.
I tried the below. I don't really know JS, but have to get this done for work.
<script type="text/javascript">
function changeClass(){
document.getElementById("en__field_supporter_emailAddress").className += " xverify_email";
}
window.onload = function(){
document.getElementsByTagName("button").addEventListener( 'click', changeClass);
}
</script>
I want the JS to insert the "xverify_email" class into the email address input line (which has the id en__field_supporter_emailAddress and also already has a class that must remain there) so that it can call the subsequent xverify JS to work.

I'm assuming you have a set of buttons, so you want to bind the event click to every button in the page:
Array.from(document.querySelectorALl('button')).forEach(function(btn) {
btn.addEventListener('click', changeClass);
});
I recommend you to embrace the attribute classList:
function changeClass() {
document.getElementById("en__field_supporter_emailAddress").classList.add("xverify_email");
}

Related

Running script after div added

Im using a plugin (Event Organiser Pro) that dynamically creates a div based on the input of a number field - basically it creates a duplicates the form fields depending on the number you enter in the input field.
I need to run some jQuery which is based on those form fields, but obviously cant run it until the div has been created.
How can i run the script once the div has been created? Is it possible to run script when div id has been created? Or something similar?
Yes, you can delegate the DOMNodeInserted event to the body.
function createDiv() {
$('<div />').addClass('test').appendTo($('body'));
}
$('body').on('DOMNodeInserted', '.test',function() {
alert('Created element .test');
})
$("button").on('click', function() {
createDiv();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Create</button>
In the example above the click on the button simulates your other script creating the div.
To rewrite the code to work with your setup you can strip the click part out and delegate the event listener to your id:
$('body').on('DOMNodeInserted', '#your_element',function() {
yourFunction();
// call a function here or add your code here directly
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Note: This example won't work here because the element with that ID does not exist and neither does the yourFunction() function.

Alter the text in the p tags

I want to alter the text in the p tags to gain (upon clicking the text) the properties set by the attribution class.
Here is the HTML:
<p onclick="function">Hello</p>
CSS:
.attribution{
color:blue;
font-weight:bold;
}
Javascript:
var main = function() {
$('<p>').text('.attribution');
};
$(document).ready(main);
Thank You!
<p onclick="function">Hello</p>
You:
Have to use the name of the function, not the keyword function which creates a new function.
Have to actually call the function, by appending () to the variable name
Shouldn't use intrinsic event attributes at all. Bind event handlers with JavaScript.
So
<p>Hello</p>
<script>
$("p").on("click", main);
</script>
var main = function() {
$('<p>').text('.attribution');
};
$(document).ready(main);
You:
Should use a function declaration (since it plays nicely with debuggers)
Need to select the existing paragraph instead of creating (and promptly discarding) a new one)
Add attribution to the classes on the element instead of replacing the text content of it with the phrase ".attribution"
Not call the function on DOM ready when you want it to be called when something is clicked
Such
function main() {
$('p').addClass('attribution');
};
As an aside, paragraphs are not designed to be interactive. While you can click on them with a mouse pointer, nothing encourages people to do so, they are outside the normal focus list (so people who don't use a mouse can't tab to them) and don't show up in screen readers as something that should be clicked on. Use appropriate markup (perhaps a button).
Okay, since your loading JQuery why no use its methods for handling click events and changing the css properties.
$( "p" ).on( "click", function() {
$(this).addClass('attribution');
});
1) You are not actually hooking any callback function to onclick event. You need to specifiy what function you want to be executed on click.
So:
HTML:
<p onclick="addClass(event)">Hello</p>
JavaScript:
function addClass(evt){
evt.target.classList.add('attribution');
}
jQuery alternative:
var main = function(){
$("p").click(function(){
$(this).addClass("attribution");
});
}
$(document).ready(function(){
main();
});

change div class,id,.. in every click

I trying to run code to change div id,class,... in every click but I don't
know how this my js code :
<div class="up_vote_bt upvote_hide" title="Delete up vote" onclick="upvoteHide()" id="hideupvote"></div>
<script>
$(document).ready(function() {
$("#upvote").click(function() {
document.getElementById("upvote").setAttribute("class","up_vote_bt upvote_hide");
document.getElementById("upvote").setAttribute("title","delete up vote");
document.getElementById("upvote").setAttribute("onclick","hideupvote()");
document.getElementById("upvote").setAttribute("id","hideupvote");
});
});
</script>
<script>
$(document).ready(function() {
$("#hideupvote").click(function() {
document.getElementById("hideupvote").setAttribute("class","up_vote_bt");
document.getElementById("hideupvote").setAttribute("title","up vote");
document.getElementById("hideupvote").setAttribute("onclick","upvote()");
document.getElementById("hideupvote").setAttribute("id","upvote");
});
});
</script>
if you're using jQuery why not do this?
$(document).ready(function(){
$('#upvote').click(function(){
//$(this) for just this element
if($(this).hasClass('upvote_hide')){
$(this).attr('title','Up vote');
upvote();
}else{
$(this).attr('title','Delete up vote');
hideupvote();
}
$(this).toggleClass('upvote_hide')
});
});
toggleClass() will either add or remove upvote_hide if it doesn't exist or exists.
attr() will alter the attribute much like setAttribute()
For my example there is no need to alter the eventHandlers or in your case setting the attribute onClick to the function. I'ts all done in the jQuery event hander function. So your functions that you're passing to the onclick attribute are called within the function.
When you attach an event handler via jQuery using the
$("#upvote").click(function() { ... });
mechanism, jQuery will directly attach the handler to the elements in the query result set. This means that the handler will be there, whatever the ID changes to in the future.
What you can do is to attach a delegated handler to the document like this.
$(document).on("click", "#upvote", function() { ... });
$(document).on("click", "#hideupvote", function() { ... });
See this article for a deeper explanation
Also, setting the onclick attribute is meaningless in this case and you should remove those lines.
However, changin IDs of elements is not a good practice. An ID should mean a unique identifier for a DOM node, which is not expected to change. I would rather toggle classes here.

Simple javascript to update a textbox when a button is hit?

I have a simple form that I'm playing around with and I'm trying to update a textbox value when a command button is clicked. The command button is called btnVerifyLocation and the textbox is called txtGeoLocation. I've attempted to do this in Javascript with the following:
The code I have is as follows:
<script type="text/javascript" id="testing">
$("btnVerifyLocation").click(function ()
{
$("input[name*='txtGeoLocation']").val("testing");
});
</script>
However when I click the button nothing happens.
A) You're missing a # in 'btnVerifyLocation' (I'm assuming that's its ID, otherwise if it's a class then use '.btnVerifyLocation'
B) Second, this should be in a $(document).ready(), otherwise you are trying to bind a click handler to a DOM element that hasn't yet been rendered.
Code should be as follows:
$(document).ready(function() {
$('#btnVerifyLocation').click(function(e) {
e.preventDefault(); // In case this is in a form, don't submit the form
// The * says "look for an input with a name LIKE txtGeoLocation,
// not sure if you want that or not
$('input[name*="txtGeoLocation"]').val('testing');
});
});
jQuery’s selector function uses CSS selector syntax, so to identify an object with an ID, you need to prefix the ID with a #:
$("#btnVerifyLocation").click(function () {
$("input[name*='txtGeoLocation']").val("testing");
});
Also just in case: You do have jQuery included, right?

How to get the id of an element ON PAGE LOAD using jQuery

I simply know how to get the id of a clicked element it's like this:
$("button").click(function(){
console.log($(this).attr("id"));
}
but what can I do for getting the id on web page load? Look at this..
$("button").ready(function(){
console.log($(this).attr("id"));
}
it returns the whole document object and this one ..
$("button").load(function(){
console.log($(this).attr("id"));
}
simply does nothing.
I want to dynamically change the styles of all buttons on load.
The main project is more complicated, and I don't want to use js core to do it, I want the simplicity of jQuery selector, but equivalent js approaches are appreciated.
i want to dynamically change the styles of all buttons on load.
If that is the case you can simply apply the css to the button selector on load, without needing to get the id of each button.
$(function() {
$("button").css("background-color", "#C00");
});
Or better yet, put the css styling into a class and just apply a class to all the buttons:
$(function() {
$("button").addClass("red-bg");
});
If you did want to get the id of each button on load, you'd need to use an array to cater for the fact there may be more than one button:
var buttonIds = $("button").map(function() {
return this.id;
}).get();
However, this is a rather pointless method as you can just use each() to iterate over the button selector anyway to get access to each indiviual button element.
you can get the all button elements in jquery and then loop on each button element to change their style -:
$(function()
{
var allButtons = $('button');
$.each(allButtons,function(index,element)
{
$(element).css('width','100px');
});
});
I think you're looking for this:
$(document).ready(function () {
$(":button").each(function () {
console.log($(this).attr("id"));
})
});

Categories

Resources