Double insert after is permitted, but before doesnt - javascript

The following html markup
<div id="parent" class="parent">
<div id="child" class="child">
<input type="text" class="text"/>
<input id="submit" value="submit" type="submit" onclick="doThis()"/>
</div>
<div>
and JS code
function doThis(){
var span= document.createElement("span");
var parent=document.getElementById("parent");
var child=document.getElementById("child");
var submit=document.getElementById("submit");
child.insertBefore(span,submit.nextSibling);
myKeys=[];
myKeys.push(getAllKeyValuePair(submit));
span.innerHTML=myKeys;
}
function getAllKeyValuePair(obj){
var str="";
for(var key in obj){
try{
str=str+"{"+key+", "+obj[key]+"}";
}
catch(e){
console.log(key);
}
}
return str;
}
JSFIDDLE example.
It works fine and it's ok to click 2,3,...etcetera times on submit button, to click on duplcate of submit button... etc. But if we trying to replace child.insertBefore(span,submit.nextSibling); to child.insertBefore(span,submit); (i.e. insert span before submit button rather than after) we can only 1 time to click to submit button. Consequent clicks will caused exception. JSFIDDLE
The question obviously is why in the case of inserting before submit second and consequent clicks will causes exception, but in the case of insert after submit it's work fine. I think, that the reason of duplicating the submit button is not true.

When you do:
span.innerHTML = myKeys;
you're creating another element with id="submit". The next time you click the button,
var submit = document.getElementById("submit");
assigns this element to the variable, rather than the one in the original HTML. This element is not a child of child, so you get an error.
The version with nextSibling also creates these duplicate IDs, but the original submit element is earlier in the DOM than the added elements, so it gets returned by getElementById and you don't get an error. I don't think there's any guarantee that this will work, since duplicate IDs aren't permitted, but it's how most browsers work.
If you don't want the string returned by getAllKeyValuePairs to be parsed as HTML, assign it to span.innerText rather than span.innerHTML.

Related

Is there a to change the value of an element using JavaScript

I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = "<a href="+intoLink+"</a>;
intoLink.value = hLink;
}
window.onload = linkIt();
<td><div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/></td></tr>
In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link
function linkIt() {
let intoLink = __C_cb_file_link.value;
let parent = __C_cb_file_link.parentNode;
__C_cb_file_link.remove();
btn.remove();
parent.innerHTML += `${intoLink}`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>
There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"</a>" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.
A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = document.createElement("a");
hLink.setAttribute("href", intoLink.value);
hLink.innerHTML = "Click here";
intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);
<td>
<div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" /></td>
</tr>
P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.
[UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with, is it what you want, right?
function linkIt() {
let fileLink = document.getElementById("__C_cb_file_link");
let hLink = fileLink.textContent;
fileLink.innerHTML = ""+hLink+"";
}
linkIt();
<div>
<p id="__C_cb_file_link">http://myLink.com</p>
</div>

Send onclick event of element without id

I'm trying to automate through my Swift3 app the click of an HTML element in line2 which lacks an 'id'.
HTML portion from website containing desired element(line2)
<div id="actionButtons" style>
<input class="pptbutton" onclick="return addSimResults();" title="SimulateRace" type="submit" value="Simulate">
Clear All = $0
<div class="holder" style="font-size:0.8em;">
<input class="pttbutton" id="graphButton" onclick="return addGraphResults();" style title="Graph your simulation" type="submit" value="Graph HvH">
...etc
I've successful automated line5's element.onclick event with the Swift code
webView.evaluateJavaScript("document.getElementById('graphButton').click();")
I've attempted to grab the element by Class name with Swift code
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0];") {
(result, error) -> Void in
print(result)
}
which returns nil. I've also tried without the "[0]".
Any suggestions how I can cause line2's Element onclick Event?
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0];")
this line of code evaluates the javascript, defined as the given string. The String is pure Javascript which selects the first element within the dom with the css class pptbutton.
You forgot to call the click method on this element, so no click is triggered by your code.
It should be:
webView.evaluateJavaScript("document.getElementsByClassName('pptbutton')[0].click();")
In this way the click event is triggered on the selected element.

Clearing a div in Jquery using its i.d

I am trying to remove the user input and replace it with the original placeholder by using the empty() function.
Here is the jQuery file which takes input from user through a <form> and appends it to list with the template() structure:
var template = function(text) {
return '<p><input type="checkbox"><i class="glyphicon glyphicon-star"></i><span>' + text + '</span><i class="glyphicon glyphicon-remove"></i></p>';
};
var main = function() {
$('.form').submit(function() {
var text = $('#todo').val();
var html = template(text);
$('.list').append(html);
$('#todo').empty();
return false;
});
};
$(document).ready(main);
After the user submits their text and it is added to the list I want the 'form' input to empty so you can enter a new item with out deleting what you just typed.
Here is a snippet of the html file that jQuery is interacting with:
<form class="form">
<div class="form-container">
<input id="todo" type="text" class="form-input" placeholder="Add item">
</div>
<button type="submit" class="btn">+</button>
</form>
Why is the line
$('#todo').empty();
not removing the user input and returning it to the original placeholder?
The empty method doesn't delete the attributes or values but it removes the html inside an element. You should use val:
$('#todo').val('');//To empty the value
If you want to remove the placeholder too then use removeAttr method:
$('#todo').removeAttr('placeholder');
.empty() is for other use cases. From the docs...
Remove all child nodes of the set of matched elements from the DOM.
Instead, you can .val('') your <input />. Observe the following simplified example...
$('.form').submit(function() {
$('#todo').val('');
return false;
});
JSFiddle Link - demo
as an observation to your neighboring code you can also pass the event and call .preventDefault() in place of return false;. Alternatively, you can call reset() in your function block as such: this.reset() - reset demo with default behavior prevented.
Try this:
$('form').trigger("reset");
This is the most elegant and correct way since it will work when you have multiple and different type of inputs without needing to do any changes. Much better than trying to empty and resetting placehorders on all fields. This will make sure to set the fields to initial state (having placeholders set too).
Based on your code you could do:
$('.form').submit(function() {
// ...
$(this).trigger("reset");
// ...
});
See it working on an example form based on yours with more fields inputs and select here.
See JQuery reset Doc here: JQuery API Doc/reset

If I hide a text input element with javascript can other javascript functions still access a value entered into it?

I am trying to use this function:
function storagecalc(){
var thediv=document.forms["boxes"];
var boxno=thediv.elements["numbofboxes"];
var howmany =0; //If the textbox is not blank */
if(boxno.value!="")
{
howmany=parseInt(quantity.value);
}
return howmany;
document.getElementById('numberprice').innerHTML = "£"+howmany;
}
To grab a value entered here:
<form action="" id="boxes">
<input type="text" id="numbofboxes" value="" name="boxnumber"/>
<button id="smtbxno" onclick="storagecalc">
<img src="images/tick.gif" alt="proceed"/>
</button>
</form>
and display it here:
<div id="grandtotal">
<p class="calctitles">
Grand Total
</p>
<p id="numberprice">
</p>
</div>
Nothing is happening when I enter a value into the textbox and click the button, is this because the button also has jQuery that hides itself and the text box upon clicking?
If not any suggestions for why it won't work?
If I hide a text input element with javascript, can other javascript functions still access a value entered into it?
Every piece of javascript that can obtain a reference to the input element (via a variable, with a DOM selector) can access its value. The visibility of that element has no effect on any of those actions. Only if you would detach it from the DOM, other functions could not select it with DOM methods.
OK, there are some errors in the document you gave us:
<button onclick="storagecalc"> does not execute anything, you will need to call the function: <button onclick="storagecalc();">. Only when assigning a listener to the onclick property with js, the function object needs to be used (document.getElementById("smtbxno").onclick = storagecalc;).
In the function itself, you use a variable quantity which is undefined (and throws an exception). I'm not sure how to fix that.
You are assigning the function but not calling it:
<button id="smtbxno" onclick="storagecalc()" ... >...</button>
------------------------------------------^
Also, members of the form's elements collection should be referenced by name, not by id.
var boxno=thediv.elements["boxnumber"];
I don't understand why you have a different name and ID, that will confuse IE which, in older versions at least, doesn't know the difference.

Not getting form-elements of external page in FireFox

I am using weblogic 8.1.6. My problrm is I have a parent page that is using Ajax to call a child page. The Child page is executed Into the Parent Page. Parent page has a form and a javascript function to read all the elements of the form but the javascript function is not able to read the elements of child page. I am using " form.elements[i].name " which is working fine in IE but not in firefox and chorme . What should i use to read the element of child page that is executed inside parenPage.
parent code
<form id="Tab">
<input type="button" onclick="alert('calling AjaX Method');" value="ADD" />
<div id="ChildOutputWillDisplayedHere"></div>
</form>`
childCode
<input class="FormFields" type = "text" name = "NameID" value = "">
click Me `
javascript code
callingJavscriptFunction(){
var form = document.forms['tab'];
for(var i=0; i<form.elements.length; i++)
{
var fieldName = form.elements[i].name;
}
}
It seems, that IE gives you all input-elements in the form, even if they didn't have name-attribute. Your input in Tab however lacks the name-attribute, which you try to read in the function. AFAIK this code will assign undefined to fieldName in IE also.
Looping like this will assign only the name of the last element in the elements-collection to your fieldName-variable. No problem with one input-element, but if there are more...

Categories