Javascript DOM setAttribute not working inside a function call - javascript

I have an HTML file with an input element to which I wish to add a new attribute, named "valid-fieldset011", which is used as a link to an AngularJS validator. The input element has the attribute id="fieldset011". If I use the following script (enclosed in script tags)
var inputElement = document.getElementById('fieldset011');
inputElement.setAttribute('valid-fieldset011', '');
everything works fine. The validator recognizes the new attribute. However, if I add the attribute onfocus="theFunction()" and invoke the following script (also enclosed in script tags)
function theFunction() {
var inputElement = document.getElementById('fieldset011');
inputElement.setAttribute('valid-fieldset011', '');
console.log("in theFunction");
}
by clicking on the input element, it doesn't work. In this case the validator is not recognizing the new attribute. But I know the function is being executed because the message "in theFunction" appears in the browser console.
Would anyone know why this is happening? I want to use the function as I want to be able to feed in the element id as a parameter.

Related

Serialising an HTML element that has event handlers

I am currently making a website for a class that I am in. It is supposed to be a store, made in Pure HTML, CSS, and JavaScript (no libraries including jQuery). I am currently attempting at making a functional cart right now. My idea is to take the element that has the information about that item (image and name, but price I kept to be constant throughout to make it simpler). From here, I thought about serialising that element and saving it to localStorage so that I can load it from the cart page. When I try JSON.serialize(product) where product is the element of the item, it only ends up with "{}" and nothing else. XMLS.serialiseToString() only gives the element without the event handler. How am I supposed to make this work?
I also tried loading the event handler in the cart page too, but I cannot figure out a way to get the HTML element from a string. Could someone tell me how to make this work? I looked at a few other questions on here but it does not make much sense to me.
Edit: I got the serialisation and deserialisation working using XMLSerializer. However, I want to change the click event handler after deserialising the element. How am I supposed to make this work?
XMLSerializer should work.
You will need to provide more code for what you're doing with local storage and your event handler but based on the info you provided, I included some code with comments below.
//this is a test click handler function to see if it still works after being added to page
function testClickHandler() {
console.log('I still work after being added to document again.')
}
//initialize XML serializer
var serializer = new XMLSerializer();
//get html element from document
var html = document.querySelector('#serializemecapt');
//convert element to string
var htmlString = serializer.serializeToString(html);
//once element is converted to string you can save in local storage
//after you retrieve the element again from local storage, use the code below to insert it into your document again
//insert element back onto page
document.body.insertAdjacentHTML('afterbegin', htmlString);
<div id="serializemecapt" onclick="testClickHandler()">Click me to see if the click event still works after I'm pushed back into the document.<br/><br/></div>
Edit: If you want to change the click handler after serialization, you can do something like this (run the snippet below and see comments):
//this function will be removed before serialization
function originalFunction() {
console.log('I am the original function before serialization.')
}
//this function will be added after serialization
function newFunction() {
console.log('I am the new function after serialization.')
}
//get html element from document
var html = document.querySelector('#serializeme');
//apply originalFunction to div using addEventListener
html.addEventListener('click', originalFunction)
//new function to demonstrate serialization
function serializeHtml() {
//initialize XML serializer
var serializer = new XMLSerializer();
//remove event listener for originalFunction before serialization
html.removeEventListener('click', originalFunction)
//serialize html
var htmlString = serializer.serializeToString(html);
//insert element back onto page
document.body.insertAdjacentHTML('afterbegin', htmlString);
//change innerText on element for example purposes
html.innerText = 'I am the same div as above after serialization. I have new text and a new function. Click me now and I will run the new function.'
//add newFunction to div using addEventListener
html.addEventListener('click', newFunction)
}
//get button element from document
var serialButton = document.querySelector('#serialButton');
//apply serializeHtml function to button using addEventListener
serialButton.addEventListener('click', serializeHtml)
<div id="serializeme"><b>Click me</b> before serializing to run the original function.<br/><br/></div>
<p><b>Click button below to serialize the div above and apply a new function to the div after serialization.</b></p>
<button id="serialButton">Serialize</button>

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

Change script data-location for a <script> inside HTML

I would like to modify one tag using javascript. I have a textbox to introduce a postcode and a button to find car parks near the position. The HTML tag is the following:
<script src="http://en.parkopedia.co.uk/js/embeds/mapView.js" data-Location="http://en.parkopedia.co.uk/parking/ST84JF/" data-options="l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2" data-size="750:400" type="text/javascript"></script>
I have two questions:
Can I modify the data-location to add the text write inside the textbox to search in that location?
Can I activate the script only when the button is clicked using javascript or jquery? The main problem here is that the should be inside the HTML code and I don't know how to put it inside the javascript file.
Code updated:
function find(){
$("script[id=script_map]").remove()
var search = document.getElementById('box_txt').value ;
$("<script />", {
"src":"http://en.parkopedia.co.uk/js/embeds/mapView.js",
"data-location":"http://en.parkopedia.co.uk/parking/" + search,
"data-options":"l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2",
"data-size":"750:400",
"id":"script_map",
"type":"text/javascript"
}).appendTo("#divId")
}
Try modifying data-location of script element before appending script element to body at click event of button element . Could alternatively use $.getScript() to retrieve script from external source
$("button").click(function() {
var val = $("input").val();
// Can I activate the script only when the button is clicked
$("<script />", {
"src":"http://en.parkopedia.co.uk/js/embeds/mapView.js",
// Can I modify the data-location to add the text write inside the textbox
// to search in that location?
"data-location":"http://en.parkopedia.co.uk/parking/ST84JF/" + val,
"data-options":"l=0&tc=0&zc=1&country=UK&ts[]=4&ts[]=3&ts[]=2",
"data-size":"750:400",
"type":"text/javascript"
}).appendTo("body")
})
Yes the data-location is simply a custom attribute i believe so just use
document.getElementById("SCRIPTTAGID").setAttribute("data-location", "newValue");
As far as activating the script to execute when a button is pressed you will need to encapse it in a function then call the function in the onClick event of the button.

form submit by clicking on anchor tag in IE11

I am trying to update some old code that works correctly on all versions of IE except IE11. When an anchor tag is clicked a javascript function is run. The function . All that the function does is that it gets certain values from the DOM and then submits a form using the post action.
I understand that IE11 submit does not work if the input element does not have a name. Here, the submit is done by clicking on an anchor tag- I tried adding a name and id to the anchor tag but it is still not working.
Any idea on how to get it to work. Following is the anchor tag.
<a class="nohigh" href="javascript:getClassDetails('<%=Id%>');">
Following is the javascript function:
function getClassDetails(a){
var classId = document.getElementById(classIdRow ).value;
var courseId = document.getElementById(courseIdRow).value;
document.getElementById('val1').value = classId
document.getElementById('val2').value = courseId
document.getElementById('clasCourseForm').submit();
}
The function that you want should be:
function getClassDetails(a){
var classId = document.getElementById(classIdRow).value; // assuming classIdRow is defined
var courseId = document.getElementById(courseIdRow).value; // assuming courseIdRow is defined
document.getElementById('val1').value = classId;
document.getElementById('val2').value = courseId;
document.getElementById('clasCourseForm').submit();
}
That's at least assuming that all the JavaScript you have up there ^ is verbatim.
[edit: removed the original answer, as the question has been changed to correct the syntax]
In addition, the JS code has other weirdness, in that the function is accepting a parameter (a) but never uses it within the function. There's almost certainly some kind of logic mistake involved there which you'll want to look into.
fixed it - by adding both a name and id to the form.

How to fix "Uncaught TypeError: Cannot call method 'appendChild' of null"

I am attempting to grab text from a HTML text area, and call the create() method when a 'Submit' button is pressed. The method is trying to use the message from the text area, and post that to its own p tag with class, and post a date stamp in its own p tag, and its own class.
These will both be in the div 'comments'. The error I am getting (using developer tools in Chrome), is
Uncaught TypeError: Cannot call method 'appendChild' of null.
This is aimed at "cmt.appendChild(divTag);". I am very new to Javascript, and this is just practise for me to increase my skills. All help is greatly appreciated!
var cmt = document.getElementById('comments');
function create() {
var username = 'User',
message = document.getElementById("textBox").value,
divTag = document.createElement('div'),
p1 = document.createElement('p'),
p2 = document.createElement('p');
divTag.className = 'comment';
p1.className = 'date';
p1.innerHTML = new Date();
divTag.appendChild(p1);
p2.className = 'message';
p2.innerHTML = username + ': ' +message;
divTag.appendChild(p2);
cmt.appendChild(divTag);
}
The error you are getting suggests that there is no element with the ID "comments" on your page. document.getElementById will return null when no element with such an ID is found, and thus cmd.appendChild(divTag) will be executed as null.appendChild(divTag).
If you are certain that the element exists, you may be executing your JavaScript that assigns the cmt variable before that element is created by the browser. To prevent that, standard practice is to place the <script> tag which includes your external JavaScript just before the closing </body> tag.
If you can't move your script tag for some reason, try running the code that assigns the variable with $(document).ready() (jQuery) or equivalent.
Your code works if the required elements exist. As you can see in this Fiddle.
Works if HTML is similar to:
<div id="comments">
<input id="textBox" type="textBox" value="Hello" />
</div>
My guess is that one of the identifiers might be misspelled or the element as you expect it does not exist.
However, if you are running the script in an external file it might try to execute before the document is fully loaded, hence your script is referring to elements not yet ready in the DOM.
In jQuery you would wrap a $(document).ready(function(){// your code here..}) around.
There is some details on how to do this in just JavaScript in this SO post: Documen Ready equivalent without jQuery.
Actually, his code is fine. Its just that JavaScript runs BEFORE HTML. A simple fix is to nest all of your code inside of a function with any name. Then use window.onload to run the function after the HTML is loaded. so basically:
window.onload = function any_name()
{
//code to be executed
}
This is useful especially if you do not want to move your script tag. I generally like to leave the tag where it is.

Categories

Resources