checkspell textbox words onkeyup event - php

I have a textbox. What I want is when user enters a word in that textbox, it should call onkeyup function and in the function we should check if spelling is correct or not.
If it is correct we don't do anything if its not we should display an alert message and remove all text from the textbox. Please tell what is the best way to do this?

This is how you would do it
function checkWord()
{
var arr = ....;
var word = document.getElementById('textbox').value;
var found = false;
for (var item in arr)
{
if(item == word)
{
found = true;
}
}
if(!found)
{
document.getElementById('textbox').value = "";
alert("Some message");
}
}
Add checkWord to the onkeyup attribute of you textbox, though I think you'd be better using onchange or onblur.
The arr variable should be written to hold an array of correctly spelt words.
Hope this helps.

Related

Jquery Change Input background color if entry matches PHP Array?

I have a simple form that has 3 fields. user, id, email.
I have 2 PHP arrays $user & $id
When a user enters there name into the user or id fields I want the respective php arrays checking and if the name or id is in the array then change the background color of the input box they are currently in.
If they update there entry then the checking should continue and if no match is found then revert the background back to it's original white color.
If they empty the input field then the color should change back to white.
The page may be preloaded with values, so I may be changing the background color using php on the initial load..
I've found this, which sort of works for the specified characters in it's array:
$('input').bind("change keyup", function() {
var val = $(this).val();
var regex = /["<>&]/g;
if (val.match(regex)) {
$(this).css("background", "red");
val = val.replace(regex, "");
$(this).val(val);
}
$("p").html(val);
});
I've tried to update it to support a php array, but it doesn't work and I don't know how to make it check either array and revert the color back.
This is what I have so far :
JFIDDLE
Thanks :)
UPDATE
I've got this working using the following :
$(function(){
$('input').bind("change keyup", function() {
var val = $(this).val();
if ($(this).attr('id')=="user") {
var check = <?php echo json_encode($user)?>;
} else {
var check = <?php echo json_encode($id)?>;
}
if ($.inArray(val, check) != -1) {
$(this).css("background-color", "red");
} else {
$(this).css("background-color", "white");
}
});
});
But is there a neater way to write this ?
Thanks :)
if you want to use your php array in javascript, you can do this:
var myArray = <?php echo json_encode($myArray) ?>;
and do the javascript magic

javascript function to validate radio buttons giving strange output.

I'm developing a quiz that pulls data out of a mysql database, and displays the results as radio buttons. The radio buttons are populated based off of key=>value and generated via a simple forloop. This has been done many times, simple google searching and research will yield all the results needed to accomplish this. The issue that I'm having, or was having (before I decided to just do this with jquery) was when I submit the form it would execute the javascript function to validate whether a button has been selected, but when you select any option other than the first radio button you'd receive the same "make a selection" alert that you would if you had not selected any buttons. Selecting the first radio button would return true and execute the getCheckedValue function call. It seems as though, the script only recognizes that I have one input type and doesn't understand to iterate through the rest of the buttons. I've refactored this function a dozen times, and still have no idea why this doesn't work.
<?php
foreach ($dataReturn as $j => $value){
echo "<input type='radio' class='answer' id='radiobtn' name='radiobtn' value='".$j."'>" .$value." </input><br/>";
}
?>
Above is the loop that generates the radio buttons (just for reference, $dataReturn is the return value of a shuffled associative array. (Which is working as intended)
When the submit button is clicked, it calls the below javascript function.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
return true;
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
}else {
alert("Make a selection.");
}
return false;
}
}
I just can't figure out why this doesn't work. As stated above, using jquery this works perfectly.
Your FOR loop: since JS uses zero-based arrays, you can't have <=, otherwise it will look for an index one higher than what you have. Use < instead;
I moved your validation for whether any fields were checked outside the loop to make management easier. It's cleaner this way than worrying about breakout out of loops in the middle of them.
Here:
function isNull() {
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i < radiobutton.length; i++) {
if (radiobutton[i].checked) {
isChecked = true;
}
}
if ( !isChecked ) {
alert("Make a selection.");
return false;
}
}
I don't know how your form tag looks, but here is what you need to prevent the form from submitting if no radio fields are checked:
<form action="" method="post" onSubmit="return isNull();">
Try the code below. You do not want your alert to fire or return false until after the for loop is finished.
function isNull(){
var isChecked = false;
var radiobutton = document.getElementsByName('radiobtn');
for (var i=0; i <= radiobutton.length; i++){
if (radiobutton[i].checked){
var answer = radiobutton[i].value;
getCheckedValue(answer);//using this just for testing selected value
return true;
}
}
alert("Make a selection.");
return false;
}
Also, your php code gives all radio buttons the same id. That is bad; doing so violates w3c standards.

form validation using javascript in changing input tags

I need to validate a form using JavaScript. The form keep changes since I am using data from a field name table to print each field (like name, address, phone no.). I'm using a loop to print the label for field and corresponding text input tag. (eg. name : textbox to enter name, phone no : textbox to enter phone no.) And at last getting these values in an array when submitting the form and entering into details table.
Following is the code for printing each field and text box:
while ($row=mysql_fetch_array($result)){
echo'<labelfor='.$row['field_name'].'name=field_id>'.$row['field_name'].':</label>';
echo'<inputtype="text" name=field_name[]id="'.$row['field_id'].'":value="'.$row['field_value'].'" size="20" class = "inpBox" >';
}
Now I need to check whether these fields are empty using JavaScript and then change the style of that particular text box. Any help will be greatly appreciated.
You'll want to hook on the submit event for your form. You could then do something like:
This is for jQuery:
$("form").submit(function{
$('input[type="text"]',"form").each(function(){
var $me = $(this);
var status = true;
if($me.val() == ""){
$me.addClass("input-validation-error");
status = false;
}
//Return status. True=Form is valid, False=Form is NOT valid
return status;
});
});
You can read more here: http://api.jquery.com/submit/
To get the values for javascript, you could do something like:
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
var me = inputs[i];
if(me.value == "") {
me.className = "input-validation-error";
}
}​
Generally Google "dynamic form validation"
For your particular case you will be interested in
See https://developer.mozilla.org/en/DOM/document.getElementsByClassName
and loop over all elements. You may want to add extra properties to your entry fields to define if it needs validation and the type of validation needed.

jquery, checkboxes within nested div onclick show/hide submit

I have a page that has a series of div's in a shopping-cart system. Each is a product, when checking the checkbox, if there are options available and/or an acknowledge checkbox to be acknowledged before form submit, then keep the button hidden and show a div with another checkbox in it, when that checkbox if exists is checked then show button.
The show hide on each div is working properly (existing code), So I am trying to create a function to be called within that function for the onclick event.
where my issue arises is the check to see if another check box [shown in the example as(tmpId == "acknowledge")] does exist and that it is checked also before they can see the submit button, if not show the submit button. This would need to work for each product they click the first checkbox on [ie("id= "+feeSID+"_checkbox")]... $("#ocContainer") is the hidden container(with submit) to show if proper checkboxes are checked.. for each product selected.
the first part of each id is a variable generated by a sql query and passed to the function..
My Function:
var feeSID = "";
var feeVAL = "";
var pop = "";
function countChecked(feeSID) {
var n = $("input:checked").val();
var tmpId = $(this).attr("name");
if (tmpId == "acknowledge") {
console.log("acknowledge Clicked <br />");
} else {
feeVAL = $(this).attr("id");
}
if (feeVAL == '') {
return;
} else {
if ($("#" + feeSID + "_checkbox:checked")) {
console.log("id= " + feeSID + "_checkbox");
var pop = $("#" + feeSID + "_popup").length;
if (pop > 0) {
$(":checkbox").click(function () {
if (tmpId == "acknowledge") {
$("#ocContainer").show();
}
});
} else {
$("#ocContainer").show();
}
}
}
}
I hope my explanation was clear. I am getting an error of:
uncaught exception: Syntax error, unrecognized expression: #[object Object]_popup
I think that the exception is possibly caused by this line in your code:
var pop = $("#"+feeSID+"_popup").length;
At some point in your code, feeSID is assigned to an object. So, you are trying to use an object as part of your selector rather than a string. You need to make sure that feeSID is a string rather than an object before you try using it as part of the selector.
The error was caused by me trying to use an Obj as part of my selector. As Adam Prax had pointed out
var pop = $("#"+feeSID+"_popup").length;
At some point in my code, feeSID is assigned to an object. I solved it by redeclaring the Variable or Object as a string before accessing it again using new String(feeSID);
This solved the issue. I hope it helps someone else, all I could find on google pointed to the use of the syntax #name="name" which is no longer valid syntax in jQuery.

Click HTML table data and insert into text area

I have a HTML table with text in the cells like so:
<tr><td>HELLO</td></tr>
I then have a text area like so:
<input type="text" id="txt_message" name="txt_message"
I want to make it so that when you click inside the table cell, the data (in this case the word 'HELLO') is inserted into the text area (so the user does not have to type it).
I dont know if this is possible, but I am guessing it is and it is 'probably' something in JavaScript.
If anybody has any advice that would be great, Thank you :)
[Working demo]
var textbox = document.getElementById('textbox');
var table = document.getElementById('table');
// add one event handler to the table
table.onclick = function (e) {
// normalize event
e = e || window.event;
// find out which element was clicked
var el = e.target || e.srcElement;
// check if it's a table cell
if (el.nodeName.toUpperCase() == "TD") {
// append it's content to the textbox
textbox.value += (el.textContent || el.innerText);
}
}​
Note: all the conditional assignments with || are for cross-browser compatibility.
Here is Working demo using jquery.
To get the value, use innerhtml and a span, more here: http://www.vbforums.com/showthread.php?t=339864
To update the textarea you should be able to do something like: document.getElementById ("text_message").value = x;
a simple jQuery snippet, assuming you have 1 textarea and multiple td's to click over
(function() {
var ta = $('#txt_message');
$('td').bind('click.addtextarea', function() {
var text = $(this).html();
ta.val([ta.val(), text].join(' ')); /* this add words */
/* ta.val(text); this print one word */
});
})()

Categories