Heyo,
Having a few issues with JavaScript function calls. Basically I am using php to create a table, and then on page init JavaScript is called to click a button which is labelled correct answer.
Now this all works fine, however when I return to the main page and try to do the same thing again it fails due to an "Uncaught TypeError: Cannot call method 'click' of null". This is happening because for some reason the script is being incorrectly called again and is then trying to click on something which isn't there, hence the 'null' error.
If I reload the page it works fine again as the JavaScript function is then not loaded until called.
The main issue seems to be that the JavaScript is remaining loaded (probably because jquerymobile uses ajax calls to load the page, and thus the data is never properly refreshed. Other than forcing the page to load without ajax, any suggestions?
JavaScript function:
function showCorrectAnswer(correctAnswer) {
$(document).on("pageinit", function() {
document.getElementById(correctAnswer).click()
})
}
PHP function:
function populatedQuestionUI ($topicID, $questionID, $actionSought) {
global $pdo;
$query = $pdo->prepare("SELECT * FROM questions WHERE Topic = ? and QNo = ?");
$query->bindValue(1, $topicID);
$query->bindValue(2, $questionID);
$query->execute();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$results[] = $row;
}
?>
<form name="questionUI" action="/MCExamSystemV2/Admin/manageQuestion.php" method="post">
<input type="hidden" name="TopicID" value="<?php echo $_POST['topic']; ?>"/>
<input type="hidden" name="QuestionNo" value="<?php echo $_POST['question']; ?>"/>
<label for="QText">Question Text</label>
<input type="text" name="QText" value="<?php echo $results[0]['QText']; ?>"/>
<label for="AnswerText-1">First Answer</label>
<input type="Text" name="AnswerText-1" value="<?php echo $results[0]['AText1']; ?>"/>
<label for="AnswerText-2">Second Answer</label>
<input type="Text" name="AnswerText-2" value="<?php echo $results[0]['AText2']; ?>"/>
<label for="AnswerText-3">Third Answer</label>
<input type="Text" name="AnswerText-3" value="<?php echo $results[0]['AText3']; ?>"/>
<label for="AnswerText-4">Fourth Answer</label>
<input type="Text" name="AnswerText-4" value="<?php echo $results[0]['AText4']; ?>"/>
<label for="CorrectAnswer">Correct answer:</label>
<div data-role="controlgroup" data-type="horizontal">
<input type="button" name="Answer-1" id="Answer-1" value=1 onClick="document.getElementById('CorrectAnswer').value='1'"/>
<input type="button" name="Answer-2" id="Answer-2" value=2 onClick="document.getElementById('CorrectAnswer').value='2'"/>
<input type="button" name="Answer-3" id="Answer-3" value=3 onClick="document.getElementById('CorrectAnswer').value='3'"/>
<input type="button" name="Answer-4" id="Answer-4" value=4 onClick="document.getElementById('CorrectAnswer').value='4'"/>
</div>
<input type="hidden" name="CorrectAnswer" id="CorrectAnswer" value='0'/>
<input type="submit" value="Confirm <?php echo $actionSought; ?>">
<input type="button" value="Cancel" onClick="location.href='/MCExamSystemV2/Admin'"/>
</form>
<script src="/MCExamSystemV2/includes/scripts.js"></script>>
<script>showCorrectAnswer('Answer-<?php echo $results[0]['CorrectA']; ?>')</script>
<?php
}
The main problem is because you're doing this:
document.getElementById(correctAnswer).click();
You're not checking if the element is on the page. Change it to:
var el = document.getElementById(correctAnswer);
if (el) {
el.click();
}
Related
This question already has answers here:
Submit form to popup window?
(3 answers)
Closed 2 years ago.
I have a PHP website that i am building where i am adding a basic product order form. I have created the form elements and once a user selects an option, i would like to open a new window (not tab), have that new window present as the focus and have variables delivered to the newly opened window through the GET method.
Currently when i submit the form, the target form opens per js, however the url variables are not passed to the new window. My code somehow concurrently also opens a new tab and transfers the GET url to the new tab and not the new window resulting in a new tab with the correct url and a new window without the correct url.
I appreciate there are many similar questions like this and i have spent hours trying to fix to no avail.
Thanks in advance for your time
Source form HTML:
<div class="prdContainer">
<form method="GET" target="_blank" action="members_order.php" onsubmit="openMemberOrder()" id='bcpot002' class="prdInput">
<div class="prodDiv">
<button type="submit" id="catOrder" class="catOrder"><img id="prdImgThumb" name="bcpot002" src="../../../Images/Product_Catalogue/bcpot002/bcpot002_thumb.jpg" ></button>
</div>
<div class="formDiv">
<label for="cat_ID" value="">Product Name:</label>
<input type="text" id="catID" name="cat_ID" value="bcpot002" readonly><br>
<label for="cat_Desc">Product Description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="Red_Pot" readonly><br>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="" readonly>
<input type="hidden" id="divHeight" name="DivHeight" value="1036" readonly>
<input type="hidden" id="divWidth" name="DivWidth" value="1543" readonly>
</div>
</form>
</div>
Source form JS:
function openMemberOrder(url) {
newwindow = window.open('members_order.php', 'members_order', 'width=1600px,height=2000px,toolbar=no,scrollbars=no,resizable=no');
if (window.focus) {newwindow.focus()}
if (!newwindow.closed) {newwindow.focus()}
return false;
}
Receiving page HTML:
<?php require_once('xxxxx/initialize.php');
$catID = $_GET['cat_ID'];
$catDesc = $_GET['cat_Desc'];
$DivHeight = $_GET['DivHeight'];
$DivWidth = $_GET['DivWidth'];
echo "ID: " . $catID . "<b>";
echo "Desc: " . $catDesc . "<b>";
echo "Val: " . $catVal . "<b>";
echo "H: " . $DivHeight . "<b>";
echo "W: " . $DivWidth . "<b>";
?>
<body>
<header id="memOrderHead" ></header>
<div class="gridContainer" id="gridContainer" ></div>
<article class="article" >
<div class="orderDiv">
<h3>Order Item</h3>
<form class="orderInput">
<label for="cat_ID">Product name:</label>
<input type="text" id="catID" name="cat_ID" value="<?php echo $catID; ?>" readonly>
<label for="cat_Desc">Product description:</label>
<input type="text" id="catDesc" name="cat_Desc" value="<?php echo $catDesc; ?>" readonly>
<label for="cat_val">Per unit price $:</label>
<input type="number" id="catVal" name="cat_val" value="<?php echo $catVal; ?>" readonly>
<label for="cat_quant">Quantity ordered:</label>
<input type="number" id="orderQuant" name="cat_quant" min="0" placeholder="0">
<label for="cat_Total">Total Price $:</label>
<input type="number" id="orderTotal" name="cat_Total" min="0" placeholder="0" readonly>
<button type="button" class="orderButton" onclick="clearForm()">Clear</button>
<button type="button" class="orderButton" onclick="total()">Calculate Total</button>
<button type="button" class="orderButton" onclick="orderConfirm()" id="confirmReset">Submit</button>
</form>
</div>
</article>
You can pass data from the webpage to a new window using HTML 5 local storage. Some other alternatives are given in the post below
JavaScript - How do I open a new page and pass JSON data to it?
I want to add a special class to each form that contains the word special as part of its action URL.
But I have many forms, and I can't think of an automated way to do this.
The only way I came up with was to create the following code, but I will have to create such code for each and every form, using a different index number:
<?php
$case1 = "special";
$case2 = "none";
if($case1 == "none") {
$class1 = ""; // don't add any class
}
else {
$class1 = "effect"; // add `effect` class
}
if($case2 == "none") {
$class2 = ""; // same goes here
}
else {
$class2 = "effect"; // and here
}
?>
HTML:
<form action="/go/<?= $case1 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class1 ?> general-class" value="submit">
</form>
<form action="/go/<?= $case2 ?>" method="POST" target="_blank">
<input type="submit" class="<?= $class2 ?> general-class" value="submit">
</form>
OUTPUT:
<form action="/go/special" method="POST" target="_blank">
<input type="submit" class="effect general-class" value="submit">
</form>
<form action="/go/none" method="POST" target="_blank">
<input type="submit" class="general-class" value="submit">
</form>
Is there any automated way to do this?
Basically I have two types of forms, one should be opened using a jquery plugin (henace the special class), and the other should open in a normal way.
My way to differentiate between them is to insert the $case[i] variable into the action url, as this is something that I have to do either way.
Perhaps there's a complete different way to achieve this, I don't know.
EDIT:
Real Form is generated mostly manually, with this code:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= $class1 ?> general-class" value="Click Me"></form>
(all variables are being given values at the start of the PHP block you see above)
There's two ways - PHP and jQuery. Based on your code, we don't have enough info to know if we can use the PHP way or not, so here's the jQuery way:
// wait until the document is ready
jQuery(function($) {
// find all forms that have "special" in the action
$('form[action*="special"]').each(
function() {
// within the form, find the submit button, and add the "effect" class
$(this).find('input[type="submit"]').addClass('effect');
}
);
});
And, the shorter / less verbose way:
jQuery(function($) {
// find all forms that have "special" in the action, find their input, and add the class
$('form[action*="special"] input[type="submit"]').addClass('effect');
});
The PHP Way
So, to do this in PHP, I would recommend writing a simple function, then calling it.
function get_class( $slug ) {
$class_map = array(
'special' => 'effect',
'none' => '',
// .. you could add others here if appropriate
return ( isset( $class_map[ $slug ] ) ) ? $class_map[ $slug ] : '';
);
Then you could use it in your php like so:
<form action="/go/<?= $item ?>/<?php echo $case1 ; ?>" method="POST" target="_blank">
<input name="a" type="hidden" value="<?php echo $a; ?>"/>
<input name="b" type="hidden" value="<?php echo $b; ?>"/>
<input name="c" type="hidden" value="<?php echo $c; ?>"/>
<input name="d" type="hidden" value="<?php echo $d; ?>"/>
<input type="submit" class="<?= get_class( $case1 ); ?> general-class" value="Click Me"></form>
While that may not seem like a big value, if you started applying those concepts to your code, you would quickly see the value start adding up.
I'm having troubles on making this work.
I need to have multiple forms on the same page... I've tried countless things, but nothing seem to work.
What I'm trying to do here is identify every form (in some way) in order to submit that one instead of the FIRST form on the page. Code below, works but submits always the same form, the first one!
Here's my current code
JS:
$(document).ready(function(){
$('.submit').on("click", function() {
var artworkId = $("#inquirebox").data("artworkid");
$.post("send.php";, $("#artinquire"+artworkId).serialize(), function(response) {
$('#success').html(response);
});
return false;
});
});
HTML:
<div id="inquirebox" data-artworkid="<?php echo 456;?>">
<form action="" method="post" id="artinquire<?php echo 456;?>" data-artworkid="<?php echo 456;?>">
<label for="name">Name:</label><br />
<input type="text" name="name" id="name" /><br />
<label for="email">Email:</label><br />
<input type="text" name="email" id="email" /><br />
<label for="message">Message:</label><br />
<textarea name="message" id="message"></textarea><br />
<input type="hidden" name="id" value="<?php echo 456;?>">
<input type="hidden" name="artist" value="<?php echo $title1; ?>">
<input type="hidden" name="url" value="<?php echo $uri1; ?>">
<input type="hidden" name="artwork" value="<?php echo $artwork1; ?>">
<input type="button" value="send" class="submit" id="submit" data-artworkid="<?php echo 456;?>">
<div id="success"></div>
</form>
</div>
You're using the same ID on all the DIV wrappers around the forms.
ID's must be unique, so you could use a class instead, but you really don't need any identifiers at all, nor do you need data attributes, the .submit button is inside the form, so all you need is this.form, or more jQuery'ish $(this).closest('form') to get the parent form
$(document).ready(function(){
$('.submit').on("click", function() {
var form = $(this).closest('form');
$.post("send.php", form.serialize(), function(response) {
form.find('.success').html(response);
});
return false;
});
});
You should however use a class on the #success element to find it based on the form.
I'm trying to write a wordpress widget but the options form is giving me some grief. The widget is designed to show an two images and a counter beneath each where the counter relies on the date. That logic is sorted.
However in a case where there is to be no counter on an image, i'm trying to put a checkbox which when checked will disable the input fields dealing with the image and counter so i can jsut read a boolean and output a simpler image with no counter.
The problem I'm having is that the JQuery that's attached to the checkbox is disabling the inputs, but i can't click it again to enable them as it just locks in its state of limbo as the checkbox gains a blue 'glow' and doesn't look checked. I don't get why the code isn't working as i expect. It's worth noting that this is my first time using JQuery, and the solution doesn't need to be JQuery if standard javascript can do the same.
I have 2 sections which will be identical in functionality, one for each image-counter pair. this is the code for one of those sections:
<h3>Anime 1</h3>
<p>
<input class="check1" type="checkbox" <?php checked($instance['s1rand'], 'on'); ?> id="rand1" name="<?php echo $this->get_field_name('s1rand'); ?>" />
<label for="<?php echo $this->get_field_id('s1rand'); ?>">Label of your checkbox variable</label>
</p>
<div class="ani1">
<p>
<label for="<?php echo $this->get_field_id('s1title'); ?>"><?php _e('Anime 1 Name:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('s1title'); ?>" name="<?php echo $this->get_field_name('s1title'); ?>" type="text" value="<?php echo $s1title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('s1date'); ?>"><?php _e('Anime 1 Start Date:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('s1date'); ?>" name="<?php echo $this->get_field_name('s1date'); ?>" type="date" value="<?php echo $s1date; ?>" />
</p>
</div>
The JQuery
jQuery(function($){
$(document).on('click', '#rand1', function(evt){
checked = $('#rand1').val();
$('div.ani1 :input').attr('disabled',checked);
return false;
});
});
EDIT: Since posting i have altered the code so that i now work with ids rather than classes, but the problem persists, even when using 3rror404's solution
New code:
<h3>Anime 1</h3>
<p>
<input class="check1" type="checkbox" <?php checked($instance['s1rand'], 'on'); ?> id="rand1" name="<?php echo $this->get_field_name('s1rand'); ?>" />
<label for="rand1">Label of your checkbox variable</label>
</p>
<div id="ani1">
<p>
<label for="s1title"><?php _e('Anime 1 Name:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="s1title" name="<?php echo $this->get_field_name('s1title'); ?>" type="text" value="<?php echo $s1title; ?>" />
</p>
<p>
<label for="s1date"><?php _e('Anime 1 Start Date:', 'wp_widget_plugin'); ?></label>
<input class="widefat" id="s1date" name="<?php echo $this->get_field_name('s1date'); ?>" type="date" value="<?php echo $s1date; ?>" />
</p>
</div>
JQuery
$('#rand1').on('change',function() {
var isChecked = $(this).prop('checked'); // this will equate to either 'true' or 'false'...
alert(isChecked); //this line doesn't work, which makes me think this function isn't working
$('#ani1 input').attr('disabled',isChecked); // ...meaning that we can use its value to set the 'disabled' attribute
});
I'm running JQuery version 1.11.1 according to the following statement:
alert(jQuery.fn.jquery);
If I understand correctly, you want all of the inputs within .ani1 to be disabled if #rand1 is checked and enabled if not checked(?). So this should work:
$('#rand1').on('change',function() {
var isChecked = $(this).prop('checked'); // this will equate to either 'true' or 'false'...
$('div.ani1 input').attr('disabled',isChecked); // ...meaning that we can use its value to set the 'disabled' attribute
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Anime 1</h3>
<p>
<input class="check1" type="checkbox" id="rand1" name="" />
<label for="rand1">Label of your checkbox variable</label>
</p>
<div class="ani1">
<p>
<label for="input1">label</label>
<input class="widefat" id="input1" type="text" />
</p>
<p>
<label for="input2"></label>
<input class="widefat" id="input2" type="date" />
</p>
...
</div>
I have the following code in PHP:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php $value = $_POST['Field1'] ?>
<input type="text" id="Field1" name="Field1" value="<?php echo $value ?>">
<input type="button" value="ButtonValue" onclick="SubmitFunction()">
</form>
And some function in JavaScript:
<script>
function SubmitFunction(){
//... do some stuff here
//But here I need to assign value to Field1:
document.getElementById("Field1").setAttribute("value", "Some value");
document.form.submit();
}
</script>
When this code loads for the first time, it says there is undefined index Field1. It's absolutely right.
But when I set attribute value to this field using SubmitFunction(), page reloads and it still can't find Field1 ! This is my problem.
I noticed that in pure HTML code the initial form looks like:
<form>
<input type="text" id="Field1" name="Field1" value>
<input type="button" value="ButtonValue" onclick="SubmitFunction()">
</form>
Where is my problem (except brain)?
<script>
function SubmitFunction(){
//... do some stuff here
//But here I need to assign value to Field1:
document.getElementById("Field1").setAttribute("value", "Some value");
document.form.submit(document.getElementById("Field1").getAttribute("value"));
}
</script>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php $value = $_POST['Field1'] ?>
<input type="text" id="Field1" name="Field1" value="<?php echo $value?$value:''; ?>">
<input type="button" value="ButtonValue" onclick="SubmitFunction()">
</form>