Send onclick event of element without id - javascript

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.

Related

Ajax: how to get values of elements with dynamicaly generatd IDs [duplicate]

This question already has answers here:
onClick to get the ID of the clicked button
(18 answers)
Closed 6 years ago.
I have a chunk of HTML code generated with PHP.
HTML looks like this:
<input type="text" id="10"><button onclick="process()">send</button>
<input type="text" id="11"><button onclick="process()">send</button> <!-- and so on until id=N -->
PHP code is like:
<?php while ($row = $result->fetch_assoc()) { ?>
<input type="text" id="<?=$row['id']?>">
<button onclick="process()">send</button>
<br>
<?php } ?>
It is supposed that if a user clicks the SEND button, the value of input tag is passed to process() function.
And here is where I'm getting stuck: I don't know which exactly ID of input should I specify in getElementById within process() fucntion - because I don't know which button is pressed.
Would be greateful for any help.
Although it is not prefered way, if you want to stick with inline event handlers, you can do something like this:
function process(elem){
alert(elem.previousSibling.value);
}
<input type="text" id="10"><button onclick="process(this)">send</button>
<input type="text" id="11"><button onclick="process(this)">send</button>
Note this
Gecko-based browsers insert text nodes into a document to represent
whitespace in the source markup. Therefore a node obtained, for
example, using Node.firstChild or Node.previousSibling may refer to a
whitespace text node rather than the actual element the author
intended to get.
previousSibling
Like previous answers, you should ideally stay away from binding the events inline. But the solution if you have to do is two, By default an event object is passed to the event handler method if it is not overridden by any one.
such a method will give you enough information about the target element of the event. (The behaviour may vary depending on the browsers so may need to test it thoroughly..)
function EventHandler(e) {
e = e || window.event;
var target = e.target || e.srcElement;
console.log(target);
}
now you can call the get the id by just doing target.id or you can basically get any attribute value.

JQUERY appending a button with onClick event and passing javascript variable in it

parameters=eval([[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]);
<input type="submit" value="Pie Chart" onClick="showChart('<?php echo $title;?>',parameters,'#container','chart','Pie Chart')"/>
this works fine when I'm just including this into my html code.
but I want to append this into a specific div using javascript or jquery. like this.
<script>
parameter=eval("[[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]");
myButton="<input type="submit" value="Pie Chart" onClick="showChart('<?php echo $title;?>',parameters,'#container','chart','Pie Chart')"/>";
$('#content').append(myButton);
</script>
My problem is, it does not perform the function whenever I click the button. Maybe because of the variable parameter that I passed and my question is how can I do this correctly? And I'm avoiding using ajax cause it will affect a big portion of my codes.
Try this : use escape characters and add parameter variable using plus operator
<script>
parameter=eval("[[\"April\",[[\"medical\",\"1\"],[\"financial\",\"4\"],[\"burial\",\"1\"]]],[\"May\",[[\"medical\",\"2\"],[\"financial\",\"6\"],[\"burial\",\"6\"]]]]");
myButton="<input type=\"submit\" value=\"Pie Chart\" onClick=\"showChart('<?php echo $title;?>',"+parameters+",'#container','chart','Pie Chart')\"/>";
$('#content').append(myButton);
</script>
jQuery('#yourbutton').on('click', function() {
}); // your on click event
//to add content to innerhtml of div:
jQuery('#divelementorother').html(jQuery('#divelementorother').html() + YourDataToInside);
First, you see the .on function of jQuery to get an event handler on click to execute function. You can append that as JavaScript to the html of div, so you doesn`t have to use the button itselfs onclick
Second, to extend the innerhtml or html of an elemnt like , you've to use .html(data) . Or, i see above my post: you can use append.
Greetings

Double insert after is permitted, but before doesnt

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.

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.

jQuery equivalent to `return document.getElementById(theVar)'

I've a javascript function
function $m(theVar){
return document.getElementById(theVar)
}
The problem with the above code is, the element I want to pass is generated by ajax so I need something like the .live() in jquery, unless it throws an error
How do I rewrite the above function in jQuery so that any DOM element generated later can also be detected.
Update:
When my page first load, it loads
1) ajaxupload.js with codes
function ajaxUpload(form,url_action,msg){
var id_element= "pop-con";
function $m(theVar){
return document.getElementById(theVar)
}
if($m(id_element)==null){
erro += "The element of 3rd parameter does not exists.\n";
}
}
2) index.php with codes
<div id="popupMargin">
<div class="close">x</div>
<div id="pop-con"></div>
</div>
<div id="ajaxGenerateMarkUp"></div>
3) now on the click of a button, the following markUp is added to the #ajaxGeneratedmarkUp div (mark-up generated through ajax)
<form onSubmit="return disableForm(this);" action="crop/wizecho_upload.php" method="post" name="f" id="wizecho" enctype="multipart/form-data">
<input id="file" type="file" name="file" onChange="return disableForm(this), ajaxUpload(this.form,'crop/wizecho_upload.php', '<br>Uploading image please wait.....<br>'); return false;"/>
</form>
Now on change of this input type file, made the call on in the javascript. Now it shows the error.
[Note: I only posted sections of code I think might affect my question]
Like this:
return $('#' + theVar)[0];
jQuery's selector can detected newly generated items:
$('#id');
So in your case:
var theVar = 'something';
$('#' + theVar); //returns a jQuery object of the select item
$('#' + theVar)[0]; //returns the first DOM object that jQuery finds with that id
I think you need to add a live call somewhere to detect the new AJAX-loaded button. This way, the button will be automatically bound to a handler that works OK as in other answers. From your comment I guess you are doing one of these:
In the AJAX-loaded button you already include some JS logic, that is not working (something like onclick="do_something").
You are binding the second button to a handler withoug the live method.
Here's a working example. Although it doesn't load contents via AJAX, it does load a dynamic button.
http://jsfiddle.net/marcosfromero/VKfKL/
Update: Another example that does load contents via AJAX and binds the newly created button with live:
http://jsfiddle.net/marcosfromero/h9RSC/

Categories