accessing selected radio button value inside iframe [duplicate] - javascript

This question already has answers here:
Accessing Elements Inside iframe and body Tags with JavaScript
(2 answers)
Closed 10 years ago.
I write the code. Where I am trying to write a form which is having a long list of radio button content inside 'iframe' like below:
<form name="iframeform" method="POST" action="http://localhost/cgi-bin/run">
<tr>
<td><iframe id="macList" src="http://localhost/macinfo" style="width:1000px;height:160px">
</iframe></td>
</tr>
<tr>
<input type="hidden" name="macaddr" value="">
<td><input type="submit" name="macselect" value="Continue" id="stdbtn" onclick="getIframeContent()"></td>
</tr>
</form>
'iframe' is pointing to macinfo page is having code like below:
<html>
<body>
<table>
<tr>
<td><input type=radio name=mac value=E8:B7:48:7B:C0:4A>abc.example.com</td>
</tr>
<tr>
<td><input type=radio name=mac value=00:17:08:5A:81:CF>xyz.cisco.com</td>
</tr>
....
</table>
</body>
</html>
How can I write "getIframeContent()" function to fetch the value of selected radio button? please help..

Long story short. To access iframe document use .contentWindow.document, i.e.:
document.getElementById('macList').contentWindow.document
And an example code:
<html>
<head>
<script type="text/javascript">
function getIframeContent(){
var myIFrame = document.getElementById('macList');
var myIFDoc = myIFrame.contentWindow.document;
var myRadios = myIFDoc.getElementsByName("mac");
var checkedItemValue = "";
for(var i=0; i<myRadios.length; i++) {
if (myRadios[i].checked) {
checkedItemValue = myRadios[i].value;
}
}
if (checkedItemValue) {
alert(checkedItemValue);
} else {alert('Select address');}
}
</script>
</head>
<body>
<iframe id="macList" src="..."
style="width:600px;height:160px">
</iframe>
<input type="submit" onclick="getIframeContent();">
</body>
</html>

You will have to get the array of mac using document.getElementsByName and loop over them:
var allRadios = document.getElementsByName("mac");
var checkedItem;
for(var i=0; i<allRadios.length; i++) {
if (allRadios[i].checked) {
checkedItem = allRadios[i];
alert('Found checked radio button');
}
}
You could then pass checkedItem to your getIframeContent function.
Edit
You could share the checkedItem variable across two pages by using window
window.checkedItem = allRadios[i];

Related

HTML form javascript to associate question, answer and feedback

I have a language quiz in an HTML form When the user checks their entry, feedback is inserted into cell in the form of a tick or cross icon . My problem is that the feedback is always inserted into the first td whether the first or second question is answered and checked. Question and appropriate answer are associated with elementNo: I can't figure out how to associate the "mark" cell with the its answer and question
<SCRIPT>
//Define the answers.
Answer = new Array( "Die Maus ist weiss.", "",
"Auf Wiedersehen!");
//inserts icon, however only in the first element named "mark".
// Somehow needs to select correct place according to element number
function itemfeedback (elementNo)
{
if (document.E1a.elements[elementNo].value == "")
{
alert("You must type an answer!");
}
else if (document.E1a.elements[elementNo].value == Answer[elementNo])
{
document.getElementById("mark").innerHTML = "<img src='correct.jpg'>";
}
else
{
document.getElementById("mark").innerHTML = "<img src='incorrect.jpg'>";
}
}
</SCRIPT>
</HEAD>
<BODY>
<FORM NAME="E1a" accept-charset="ISO-8859-1" onReset="return confirm('Clear entries? Are you sure?')">
<HR>
<H3>
translate, remembering punctuation and capitalisation...
</H3>
<table>
<tr>
<td>1. The mouse is white.</td>
<td><INPUT TYPE="TEXT" NAME="Q1" SIZE=50 MAXLENGTH=50></td>
<td><INPUT TYPE="button" id ="check_button" VALUE="check..." NAME="B1" onClick="itemfeedback(0)"></td>
<td id="mark"></td>
</tr>
<tr>
<td>2. Good-bye!</td>
<td><INPUT TYPE="TEXT" NAME="Q2" SIZE=50 MAXLENGTH=50></td>
<td><INPUT TYPE="button"id ="check_button" VALUE="check..." NAME="B2" onClick="itemfeedback(2)"></td>
<td id="mark"></td>
</tr>
</table>
<hr>
<INPUT TYPE="RESET" id ="reset_fields" VALUE="Clear Entries">
</CENTER>
</FORM>
</BODY>
</HTML>
I hope that my question is clear and that someone will help.
Quick Answer
ID's are intended to be unique within a HTML document according to HTML5 specs. Because of this, all instances of an ID after the first occurrence are ignored by JavaScripts "getElementById" function. A more proper way to select multiple DOM elements is to use the "class" attribute, like this:
<td class="mark"></td>
...
<td class="mark"></td>
And reference it using JavaScript, using "getElementsByClassName"
document.getElementsByClassName('mark')
More Helpful Answer
I would make a couple more suggestions, to make your code a bit more dynamic, and functional. I have inserted comments in the code below to explain the changes/suggestions I have.
<html>
<head>
<script>
// We will use an object instead of an array, so that we can reference the answers by a string, rather then an integer.
// Also, any time a NEW variable is defined, it should be prefaced with "let" or "const" for >= ES2015, or "var" for < ES2015 (see https://codeburst.io/javascript-wtf-is-es6-es8-es-2017-ecmascript-dca859e4821c for details on the different script versions)
const answer = {
Q1: "Die Maus ist weiss.",
Q2: "Auf Wiedersehen!"
};
// itemfeedback function is now passing the input id, rather than the index
function itemfeedback (id) {
// This will get the input, associated with the button
let input = document.getElementById(id),
// This will be the ID of the mark element that is associated with the submitted input
markId = "mark" + id,
// This is the mark element assocaited with the submitted input
mark = document.getElementById(markId);
if (input.value == "") {
alert("You must type an answer!");
}
// Since we have assigned the answers to an object, and gave each of the answers indexes to match the input ids, we can find the answer by that
else if (input.value == answer[id]){
mark.innerHTML = "<img src='correct.jpg'>";
} else {
mark.innerHTML = "<img src='incorrect.jpg'>";
}
}
</script>
</head>
<body>
<form NAME="E1a" accept-charset="ISO-8859-1" onReset="return confirm('Clear entries? Are you sure?')">
<HR>
<H3>
translate, remembering punctuation and capitalisation...
</H3>
<table>
<tr>
<td>1. The mouse is white.</td>
<!-- Gave input ID of "Q1" -->
<td><input TYPE="TEXT" NAME="Q1" SIZE=50 MAXLENGTH=50 id="Q1"></td>
<!-- Changed id to class, since it is non-unique -->
<td><input TYPE="button" class="check_button" value="check..." NAME="B1" onClick="itemfeedback('Q1')"></td>
<!-- We will give this an ID that can be associated with it's related inputs name attribute -->
<td id="markQ1"></td>
</tr>
<tr>
<td>2. Good-bye!</td>
<!-- Gave input ID of "Q2" -->
<td><input TYPE="TEXT" NAME="Q2" SIZE=50 MAXLENGTH=50 id="Q2"></td>
<!-- Passed ID to onChange handler, instead of index. Also hanged id to class, since it is non-unique -->
<td><input TYPE="button" class="check_button" value="check..." NAME="B2" onClick="itemfeedback('Q2')"></td>
<!-- We will give this an ID that can be associated with it's related inputs name attribute -->
<td id="markQ2"></td>
</tr>
</table>
<hr>
<input TYPE="RESET" id="reset_fields" value="Clear Entries">
</center>
</form>
</body>
</html>
EDIT for Form Reset
Place this function to remove images from form onReset:
<!-- We are now calling a function to be executed, and the returned value of the function will determine if the form itself is cleared. A negative blue will not, a positive value will -->
<form NAME="E1a" accept-charset="ISO-8859-1" onReset="return clearForm(this)">
function clearForm (form) {
// Get option that is pressed
var clear = confirm('Clear entries? Are you sure?');
// If positive option is clicked, the form will be reset
if (clear) {
// This will select all images within the document
var markImgs = document.getElementsByTagName('img');
// Iterates through each image, and removes it from the dom
while (markImgs[0]) markImgs[0].parentNode.removeChild(markImgs[0])
}
return clear;
}

Collecting values of multiple checkboxes using jQuery

For convenience I'm giving the script and the html in one place (instead of separate .js file). After selecting any check checkboxes if I click the "edit" link then the alert keeps repeating in a loop and the no of selected checkboxes are reported as 0 1 2 3 4 5 .... in successive occurences. Anybody's help in this matter will be appreciated.
<!doctype html>
<html>
html>
<head>
<title>Cities</title>
<script type="text/javascript" src="jquery-3.2.1/jquery-3.2.1.min.js"></script>
<script type = "text/javascript">
var jq = jQuery.noConflict();
var ids = new Array();
jq(document).ready(function () {
jq("#edit").click(function(){
jq('input[name="cid"]:checked').each(function() {
ids.push(parseInt(jq(this).val()));
}); // end checked each
if(ids.length > 0)
alert(ids.length + " cities selected \n"+"their names: "+ids);
else
alert("Please select one or more rows to edit.");
}); // end #edit click
}); // end document ready
function setCityUpdateAction(){
jq("#edit").click();
}
</script>
</head>
<body>
<form name="myform">
<table border=1px>
<tr><th></th>select<th>CityID</th><th>City</th></tr>
<tr><td><input type="checkbox" name="cid" value=1></td>
<td>1</td><td>London</td></tr>
<tr><td><input type="checkbox" name="cid" value=2></td>
<td>1</td><td>New York</td></tr>
<tr><td><input type="checkbox" name="cid" value=3></td>
<td>1</td><td>Paris</td></tr>
<tr><td></td><td></td><td><a id="edit" href="#" onclick="setCityUpdateAction();">edit</a></tr>
</table>
</form>
</body>
</html>
You already have click event handler when you write jq("#edit").click. So you need to get rid of onclick event handler in the <a> tag.
So, it should look like this:
<a id="edit" href="#" >edit</a>
Additionally, you can get rid of function as well due to click event handler already set. So remove below function.
setCityUpdateAction() {
jq("#edit").click();
}
try this:
<!doctype html>
<html>
<head>
<title>Cities</title>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type = "text/javascript">
var jq = jQuery.noConflict();
jq(document).ready(function () {
jq("#edit").click(function(){
var ids = new Array();
jq('input[name="cid"]:checked').each(function() {
ids.push(parseInt(jq(this).val()));
}); // end checked each
if(ids.length > 0)
alert(ids.length + " cities selected \n"+"their names: "+ids);
else
alert("Please select one or more rows to edit.");
setCityUpdateAction()
}); // end #edit click
}); // end document ready
function setCityUpdateAction(){
jq("#edit").click();
}
</script>
</head>
<body>
<form name="myform">
<table border=1px>
<tr><th></th>select<th>CityID</th><th>City</th></tr>
<tr><td><input type="checkbox" name="cid" value=1></td>
<td>1</td><td>London</td></tr>
<tr><td><input type="checkbox" name="cid" value=2></td>
<td>1</td><td>New York</td></tr>
<tr><td><input type="checkbox" name="cid" value=3></td>
<td>1</td><td>Paris</td></tr>
<tr><td></td><td></td><td><a id="edit" href="#">edit</a></tr>
</table>
</form>
</body>
</html>
First declare the ids array inside the jq("#edit").click event, second remove the onclick from a tag and call the setCityUpdateAction function inside your jq("#edit").click event.
I hope this will help you.
Make sure you reset the ids array, Also serialize the form values,
Make sure you name every inputfield! It can be achieved with serializeArray() like this:
var $form = $(form).serializeArray();
$.each($form, function(i, field) {
...
});
Javascript
var jq = jQuery.noConflict();
jq(document).ready(function () {
jq("#edit").click(function(){
var $form = jq(myform).serializeArray();
var ids = new Array();
jq.each($form, function(i, field) {
ids.push(parseInt(field.value)+"-"+field.name);
});
if($form.length > 0)
alert($form.length + " cities selected \n"+"their names: "+ids);
else
alert("Please select one or more rows to edit.");
}); // end #edit click
}); // end document ready
HTML
<form name="myform">
<table border=1px>
<tr><th></th>select<th>CityID</th><th>City</th></tr>
<tr><td><input type="checkbox" name="london" value=1></td>
<td>1</td><td>London</td></tr>
<tr><td><input type="checkbox" name="newyork" value=2></td>
<td>2</td><td>New York</td></tr>
<tr><td><input type="checkbox" name="paris" value=3></td>
<td>3</td><td>Paris</td></tr>
<tr><td></td><td></td><td><a id="edit" href="javascript:;">edit</a></tr>
</table>
</form>
See here how it is done: jsFiddle

JS validation troubles and some more gimmicks

I've already have validated my form using php but I would like to change it to use javascript.For some reason it doesn't seem to work, and I cannot understand why.
<form name="adminFormNewMember" method="post" action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>>
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter()" required autofocus></td>
</tr>
</table>
</form>
---------------------
<script>
function allLetter()
{
var text = document.getElementById("firstname");
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
return true;
}
else
{
alert("message");
return false;
}
}
</script>
Obviously the form contains more stuff, I've omitted them for the sake of clarity.
Also I'd like to use the same function for more field such as lastname etc, but I don't know how to do that since I'm using the getElementById
Finally, I'd like to just highlight the textfield red for errors, green for correct etc.
Clarification Edit I still need the PHP part I just don't want it to validate. I need the validation to happen for each field onBlur, and then the data to be passed to the php function to be inserted in a DB etc.
Try this :
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<form name="adminFormNewMember" method="post" >
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" onblur="allLetter(this.id)" required autofocus></td>
</tr>
</table>
</form>
<script>
var allLetter = function(id){
var text = document.getElementById(id).value;
if(text.length ==0 || text.toUpperCase().replace(/[^A-Z]/g, "").length != text.length) alert("Incorrect value")
}
</script>
</body>
</html>
To use your function with several fields, just pass the id as a parameter (this.id), in allLetters function, pass the parameter to getElementById.
It seems your Regexp is not correct (or suffiscient), so first check the field is not empty then check if length of value equals lenngth of value with letters only. If so the field is correct, otherwise go for the alert.
Maybe you should consider using jquery and the validate plugin here witch can save you lot of time
Returning true or false in your sample code is achieving nothing. What you need to do is, depending on whether validation is successful or not, add a CSS class to your input field. This CSS class should handle either background or border for your field to indicate that it did not match the criteria.
Instead of using onblur attribute, create an event listener for the blur event on your form fields. Delegate this listener to transfer control to a function which will take the value inside the event target and validate it. This should make your code more modular and apply to most fields.
Here is some code in basic javascript:
<table id="tableNewUser">
<tr>
<td>First Name </td>
<td><input type="text" id="firstname" class="formFields"></td>
<td>Last Name </td>
<td><input type="text" id="lastname" class="formFields"></td>
<td>Fathers Name</td>
<td><input type="text" id="fathername" class="formFields"></td>
</tr>
<script>
for(var i=0; i < document.getElementsByClassName("formFields").length ; i++){
document.getElementsByClassName("formFields")[i].addEventListener("blur", function(evt){
var text = evt.target;
var letters = /^[A-Za-z]+$/;
if(text.value.match(letters))
{
evt.target.classList.remove('incorrectField');
evt.target.classList.add('correctField');
}
else
{
evt.target.classList.add('incorrectField');
evt.target.classList.remove('correctField');
}
});
}
<style>
.incorrectField{
background: red;
}
.correctField{
background: green;
}
</style>

Update price shown onchange

I am simply trying to get a price shown, to update on an onchange event. Right now, this is only just showing me both values of the onchange ids I'd just like to have someone click a check box and then it updates the price that was already shown to the new value.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<table>
<tr>
<td>
<input type="checkbox" id="extras" value="25.00" onChange="calc()">
</td>
<td>
<input type="checkbox" id="rush" value="35.00" onChange="calc()">
</td>
<td>
<input id="total" type="text" value="90.00" />
</td>
</tr>
</table>
</body>
<script type='text/javascript'>
function calc() {
var extras = document.getElementById('extras').value;
var rush = document.getElementById('rush').value;
var result = document.getElementById("total");
result.value = extras + rush;
}
</script>
</html>
You can do:
$('input[type=checkbox]').change(function () {
var val = parseFloat(this.value),
totalVal = parseFloat($('#total').val());
if (this.checked) {
$('#total').val((totalVal + val).toFixed(2));
} else {
$('#total').val((totalVal - val).toFixed(2));
}
});
Fiddle Demo
a non jquery solution could be to check for checked value. You also need to convert the value which is text to float otherwise it won't be a valid sum but just concatenation of strings.
var extrasCB = document.getElementById('extras');
var extras = 0;
if(extrasCB.checked) {
extras = parseFloat( extrasCB.value );
}

How to add javascript data to mysql?

I have problem how to add this javascript data to mysql database?
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count +1 ;
document.getElementById("likes").innerHTML = count;
}
</script>
<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>
<div id="likes">0</div>
You need to use mysql-real-escape-string while inserting your js code to mysql db. Assign your code string to a variable and use mysql-real-escape-string while inserting db. Example usage;
HTML:
<form action="save_code.php" method="POST">
<table>
<tr>
<td>Code</td>
<td><textarea name="code"></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Save" value="Save"/></td>
</tr>
</table>
</form>
PHP: save_code.php
// Comment out this for real test
//$jsCode = $_POST['code'];
//Assign js code string to variable
$jsCode = '<script type="text/javascript">
var count = 0;
function countClicks() {
count = count +1 ;
document.getElementById("likes").innerHTML = count;
}
</script>
<input type="button" value="Like "onclick="javascript:countClicks();" alt="alt text"/>
<div id="likes">0</div>';
$link = mysql_connect('mysql_host', 'mysql_user', 'mysql_password')
or die(mysql_error());
$query = "INSERT INTO your_table(id, code) VALUES('', mysql_real_escape_string($jsCode))";
mysql_query($query);
You have 2 ways to do:
1- AJAX
You must make a SaveData.php for example and make a ajax Post to this page and then insert in database.
2- JS to PHP
In the same page you do this
Insert into TABLE (count) VALUES (".<script> write(count); </script>.");

Categories