function compare with variable in mysql - javascript

<?php $check=$ word[ 'Word'][ 'en_words']; ?>
<form id="" method="post" action="">
<label>
<span id="first"><?= $check; ?></span>
<span>EN:</span>
<input type="text" id="second" />
</label>
<input type="button" class="button" value="Check" onclick="validate()" />
<script>
function validate() {
var first = document.getElementById('first').value;
var second = document.getElementById('second').value;
if (second == first) {
alert('Ok!');
} else {
alert('No!');
}
}
</script>
Why this script doesn't work, could someone see?
I want compare variable with input to $check (mysql record).

You didn't told us what the expected result is.
Anyway, I see that you use a document.getElementById('first').value on a ''. This funcion only works with form elements.
You should use something like: document.getElementById('first').innerHTML. So, your code should look like:
....
<script>
function validate(){
var first = document.getElementById('first').innerHTML;
var second = document.getElementById('second').value;
if (second == first){
alert('Ok!');
}
else {
alert('No!');
}
}
</script>

Ensure that the $check variable is being printed. You may need to echo or print the variable:
<span id="first"><?php print $check; ?></span>
Also, the span element does not contain a value. Instead, try capturing the value with innerHTML:
var first = document.getElementById('first').value;

Since first is html tag so it will have innerHtml and second is input so it will have value
<script>
function validate(){
var first = document.getElementById('first').innerHTML;
var second = document.getElementById('second').value;
if (second == first){
alert('Ok!');
}
else {
alert('No!');
}
}
</script>
<button onclick="validate()">Click</button>

Related

checking value for element causing error on onsubmit

I have a form which I am trying to check color of the element before the page submits. I am trying to validate the form using a function called by the from using 'onsubmit='. If I add 'document.getElementById(name).style.backgroundColor' in the code below, when I submit the page it will go directly to the next page without asking if I want to go onto the next page or letting the user know the form has errors. It looks like the form is successfully calling both validate() and check_form() functions, but with the background color check it seems to not complete the validate() function. I've tested it without the 'style.backgroundColor' and it works fine (gives notice to user). What am I doing wrong?
Thanks
Simplified example of the code used:
<!DOCTYPE html>
<html>
<body>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="sample" name="sample" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
var sample = 'sample';
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
if(sample.style.backgroundColor == 'red'){
return 'false';
}
else{
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
test example of check_form function that does work:
function check_form(){
sample = document.getElementById(sample);
return 'false';
}
Edit: The way I have my form set up now is more accurately displayed as:
<!DOCTYPE html>
<html>
<body>
<?php $sample = 'test'; ?>
<form class="bulk" onsubmit="return validate(this)" action="next_page.php" method="GET">
<input type="checkbox" id="checkbox" name ="checkbox">
<input type="text" id="<?php echo $sample;?>" name="<?php echo $sample;?>" value="">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
var checkbox_name = 'checkbox';
sample = <?php echo json_encode("$sample"); ?>;
sample = document.getElementById(sample);
//if checkbox is checked, make sure all the required fields are there
$("#"+checkbox_name).change(function(){
if(document.getElementById(checkbox_name).checked){
sample.style.backgroundColor = "red";
}
});
});
function validate(from) {
var valid = 'true';
if(check_form() == 'false'){
valid = 'false';
}
if(valid == 'false'){
alert('ERROR: Some inputs are invalid. Please check fields');
return false;
}
else{
return confirm('Are you sure you want to submit?');
}
}
function check_form(){
sample = document.getElementById(sample);
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
</script>
<input type='submit' id="sub" name ="submit" value='Update Samples' />
</form>
Where the samples are brought in from another page to dynamically create the form.
sample is a local variable in the dom ready handler which is not accessible in the check form method, but since sample is an id of an element that will be available as a window property(global variable), so you will be getting an error like Uncaught TypeError: Cannot read property 'style' of null.
Instead pass the id as a string literal in the check_form method like
function check_form() {
var sample = document.getElementById('sample');
console.log(sample.style.backgroundColor)
if (sample.style.backgroundColor == 'red') {
return 'false';
} else {
return 'true';
}
}
Demo: Fiddle

Javascript/PHP Validation

I'm trying to prevent the form being submitted if the validation fails, however its not working at the moment. The onclick method is used for hidden input, but its the onsubmit method that is failing. Any ideas?
<input type="submit" class="btn ccm-input-submit" id="register" name="register" value="Register" onsubmit="return validation(this)" onclick="copytextbox()"/>
<?php echo $form->hidden('rcID', $rcID); ?>
<script>
function copytextbox()
{
var textToCopy = document.getElementById('school').value;
var whereToCopy = document.getElementById('<?php echo $school ?>');
whereToCopy.value += textToCopy;
}
function validation(f)
{
var schoolText = document.getElementById('school').value;
if (schoolText == '') {
alert('Please Choose a value from the dropdown box.');
return false; // stop submission until textbox is not ''
} else {
f.submit();
return false;
}
}
</script>
Also, im attempting to see if that value is a member of an array, I tried using indexOf(schoolText) etc but this also failed, kind regards
Move your onsubmit="return validation(this)" attribute from the <input> tag to the <form> tag.
Test an array like this:
// global array
var fruits = ["Banana", "Orange", "Apple", "Mango"];
function findFruit(val) {
if(fruits.indexOf(val) == -1 {
alert('not found');
} else {
alert('Found!')
}
}
findFruit('Peach'); // not found

function not working in jsp page?

<script>
function KeepCount() {
var x=0;
var count=0;
var x;
for(x=0; x<document.QuestionGenerate.elements["questions"].length; x++){
if(document.QuestionGenerate.elements["questions"][x].checked==true || document.QuestionGenerate.elements["option"][x].checked==true || document.QuestionGenerate.elements["Description"][x].checked==true || document.QuestionGenerate.elements["fillups"][x].checked==true){
count= count+1;
document.getElementsByName("t1")[0].value=count;
}
else
{
document.getElementsByName("t1")[0].value=count;
//var vn=$('#t1').val();
// alert(vn);
//alert(vn);
//alert("value is"+count);
}
}
// var cc = document.getElementsByName("t1")[0].value;
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
}
</script>
<form action="SelectedQuestions.jsp" method="post" name="QuestionGenerate">
<input type="text" name="t1" id="t1" value="">
<input type="submit" id="fi" name="s" value="Finish" onclick="return KeepCount();">
</form>
I use the above code for checking how many check box are checked in my form my form having many check box. and if no check box are selected means it shows some message and than submit the form but for loop is working good and textbox get the value after the for loop the bellow code doesn't work even alert() is not working
**
var vn=$('#t1').val();
alert(vn);
if(vn==0){
alert("You must choose at least 1");
return false;
}
This code is not working why?
**
I change my KeepCount() function code shown in bellow that solve my problem
function KeepCount()
{
var check=$("input:checkbox:checked").length;
alert(check);
if(check==0)
{
alert("You must choose at least 1");
}
return false;
}
The bug is : document.QuestionGenerate.elements["questions"] it is undefined that's why the code is not even going inside for loop use instead :
document.QuestionGenerate.elements.length

Use one jQuery function multiple times for several form inputs

I got a question in which I hope someone can help me
I have this script:
File test.php:
<script>
$(document).ready(function() {
var min_chars = 1;
var characters_error = 'Write at least '+ min_chars +' character';
var checking_html = 'Getting information...';
$('#get_information').click(function(){
if($('#idprice').val().length < min_chars){
$('#results_gotten').html(characters_error);
}else{
$('#results_gotten').html(checking_html);
check_availability();
}
});
});
function check_availability(){
var idprice = $('#idprice').val();
$.get("check_idprice.php?id="+$("#idprice").val(), function(data){
$("#results_gotten").html(data);
$("#results_gotten").show();
});
}
</script>
<input name="idprice" type="text" id="idprice" />
<input type="button" id="get_information" value="Checar"><br>
<div id="results_gotten"></div>
And a second file check_idprice.php
if (isset($_GET['id'])) { $id = $_GET['id']; } else { die ('No information'); }
$result = mysql_query("SELECT * FROM `sm_prices` WHERE `productid` = '". $id ."'");
$noresults = mysql_num_rows($result);
if($noresults > 0){
echo $noresults." found";
}else{
echo "No results found";
}
And it works perfectly, you can see it in action here:
http://www.enteratenorte.org/starmexico/test.php (You can search of 15-1 to get a result)
or here:
http://jsfiddle.net/EnterateNorte/hpT66/ (wont get you any result since it need a DB)
How ever, I would like to have multiple filds in the same test.php file, something like this:
<input name="idprice1" type="text" id="idprice1" />
<input type="button" id="get_information1" value="Check"><br>
<div id="results_gotten1"></div>
<input name="idprice2" type="text" id="idprice2" />
<input type="button" id="get_information2" value="Check"><br>
<div id="results_gotten2"></div>
<input name="idprice3" type="text" id="idprice3" />
<input type="button" id="get_information3" value="Check"><br>
<div id="results_gotten3"></div>
It could be 3 or more fields
How can this be achived using one single code?
You could wrap each block in a parent DIV:
<div class="retrieveInfo">
<input name="idprice1" type="text" id="idprice1" class="retrieveInfoText" />
<input type="button" id="get_information1" class="retrieveInfoSubmit" value="Check"><br>
<div id="results_gotten1" class="retrieveInfoResults"></div>
</div>
Then your JS might look something like this:
<script>
$(document).ready(function() {
var min_chars = 1
, characters_error = 'Write at least '+ min_chars +' character'
, checking_html = 'Getting information...'
, infoContainer = $('.retrieveInfo'); // this selects all the containers with this css class
/// now you can loop through each of the containers found...
infoContainer.each(function(){
var self = $(this) // $(this) refers to the current "container"
, infoSubmit = self.find('.retrieveInfoSubmit') // find button
, infoText = self.find('.retrieveInfoText') // find text box
, infoResults = self.find('.retrieveInfoResults'); // find result div
// since this is a loop, this click handler will be attached to all buttons found
infoSubmit.click(function(e){
// stop the browser from submitting the form (default action)
e.preventDefault();
// check if the info validates
if( infoText.val().length < min_chars){
infoResults.html(characters_error);
// returning here will stop execution of the function, no need for else
return false;
}
infoResults.html(checking_html);
// modified the funciton to accept some arguments
check_availability(infoText.val(), infoResults);
});
});
});
/**
* checkVal is the user input
* resultDiv is the jQuery object that points to the results for this container
*/
function check_availability(checkVal, resultDiv){
$.get("check_idprice.php?id=" + checkVal, function(data){
resultDiv.html(data).show();
});
}
</script>
Try something similar to the following
for(var i=0;i<3;i++) {
$('#get_information'+i).click(function(){
if($('#idprice'+i).val().length < min_chars){
$('#results_gotten'+i).html(characters_error);
}else{
$('#results_gotten'+i).html(checking_html);
check_availability(i);
}
});
}
function check_availability(i){
var idprice = $('#idprice'+i).val();
$.get("check_idprice.php?id="+$("#idprice"+i).val(), function(data){
$("#results_gotten"+i).html(data);
$("#results_gotten"+i).show();
});
}

How to disable input attribute after 10 clicks?

I am trying to remove the style or the background of a textbox to reveal the content after 10 clicks. How can I do that on Javascript?
here is my html:
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000">
and here is my JS:
function check() {
var tries++;
if (tries == 10){
document.getElementById('firstN').disabled= true;
}
}
The problem is that tries is a local variable (local to the check function). Every time check is called, a new variable named tries is created and initialized to 0.
Try this instead:
var tries = 0;
function check() {
tries++;
if (tries == 10) {
document.getElementById('firstN').style.background = '#ffffff';
}
}
(I'm assuming that you already have some code to call check when the element is clicked. If not, you need to add a click handler to your element.)
You are instantiating a var "tries" everytime you go into this function. Move the variable up a level to where it will increment:
var btn = document.getElementById("btnclick");
btn.onclick = check;
var tries = 0;
function check() {
tries++;
if (tries == 10){
var ele = document.getElementById("firstN");
ele.value= "DISABLED";
ele.disabled = true;
}
}​
EDIT:
Working JSFiddle
store it in a cookie:
<script type="text/javascript">var clicks = 0;</script>
<input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" value="Click" onclick="clicks++">
onclick="$.cookie('clicks', $.cookie('clicks') + 1);"
Here you go. Remove the alert lines when you see that it works.
<html>
<head>
<title>Test</title>
<script>
function check(){
var getClicks = parseInt(document.getElementById('firstN').getAttribute('clicks')); //Get Old value
document.getElementById('firstN').setAttribute("clicks", 1 + getClicks); //Add 1
if (getClicks === 10){ //Check
alert('Locked');
document.getElementById('firstN').disabled= true;
} else {
alert(getClicks); //Remove else statement when you see it works.
}
}
</script>
</head>
<body>
<form action="#">
Input Box: <input id="firstN" type="text" style="color:#FF0000; background-color:#FF0000" onclick="check();" clicks="0">
<input type="submit" name="Submit" value="Submit">
</form>
</body>
</html>

Categories