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();
});
}
Related
I'm using codeigniter 3.0.4 and now stuck on a basic problem. I have an <input type='text'> with a default value generated using Jquery.
My Question, how do I check whether the value has been changed or not when I submit a form?
If the value now is different from default given value, it'll do a callback validation (it's actually to check email availability). Otherwise if the value is still the same as the default given value it will skip the callback validation.
This is my modal
<div class="modal-body" id="myModalBody">
<form id="contactform" role="form" method="POST" action='<?php echo base_url('administrator/kategori/editcategory');?>' >
<div class="form-group">
<label for="kategori"> Nama Kategori </label>
<input type="hidden" name="id" class='id' id='id'>
<input type="text" class="form-control edit-category" name='edit-category' id="edit-category" required autofocus>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success confirm-edit"> Edit Data </button>
</form>
</div>
as you can see, that form above submits the data to administrator/kategori/editkategori
and this is my editkategori() function
public function editcategory(){
if($this->input->post()){
$this->form_validation->set_rules('kategori', 'Kategori Baru', 'required|callback_correctcategory');
if($this->form_validation->run() == FALSE){
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
} else {
$tobesent = array(
"id" => $this->input->post('id'),
"kb" => $this->input->post('kategori')
);
$result = $this->admincrud->editcategory($tobesent);
if($result){
$this->session->set_flashdata('result', 'Kategori Sukses Diubah');
redirect('administrator/kategori');
}
}
} else {
redirect('administrator/kategori');
}
}
This is the JQuery function to automatically give values to corresponding text when the modal above is shown
$('.toggle-edit-modal').click(function(){
var id = $(this).closest('tr').find('td:eq(0)').text();
var categoryname = $(this).closest('tr').find('td:eq(1)').text();
$('.id').val(id);
$('.edit-categoryname').val(categoryname);
})
in the set of validation rules, I put the callback correctcategory(), and this is the correctcategory() function :
public function correctcategory($str){
$sterilizedkey = strtoupper(trim(str_replace(" ", "", $str)));
$tobeshown = ucfirst(strtolower($sterilizedkey));
$this->CI->db->select("upper(trim(REPLACE(`CategoryName`, ' ',''))) as `CategoryName`");
$this->CI->db->from('category');
$result = $this->CI->db->get()->result_array();
$data = array();
foreach ($result as $key => $value) {
$data[] = $value['CategoryName'];
}
if(in_array($sterilizedkey, $data)){
$this->set_message('correctcategory', 'The faculty has been registered before');
return false;
} else {
return true;
}
}
With the code above, the system will evaluate every value submitted through the form.
The problem comes when I open the modal, and a textbox with default given value appears. How can I skip the correctcategory validation if I directly submit the form but without changing the value of the textbox, or when the new value and the old given one are exactly the same ?
you have to store the original value in a hidden text box. and check it with the text box which has values.
for eg:
<input type="text" id="orig" value="your email">
<input type="hidden" id="hid" value="your email">
then in jquery on submit check like the following
var original = $('#orig').val();
var static = $('#hid').val();
if(original == static){
alert("not changed");
}else{
alert("changed");
}
Note: this code is only for example as you did'nt shared any of your code
If the value being set by Jquery is known by you, then the controller should as well be aware( guess this is the category database value)
Based on the assumption that default value is known.
To solve this, the controller function needs to be aware of the default value you are setting for the input.
class Categories extends CI_Controller {
public function edit()
{
// form submited?
If ( $this->input->post())
{
$this->load->model('category_model');
$error = null;
$success = false ;
$id = $this->input->post('id');
// now you were looking for 'kategori' instead of 'edit-category'
$posted_cat_name = $this->input->post('edit-category');
// get the db record
$category = $this->category_model->fetch( array('id' => $id ));
if( !$category->id)
{
$error = 'Category not exist' ;
// set flash and redirect
redirect('categories/admin_list');
}
// category remain the same
If( $posted_cat_name == $category->name)
{
$error = "No changes made" ;
}
else if( $this->category_model->update($id , $posted_cat_name) == false)
{
$error = 'Error occured updating category' ;
// get the error and log_message() for debuging
}
else
{
$success = true ;
// set flash data and redirect
}
}
// do you need this remaining code? aren't you suppose to redirect back to admin list where the form was posted ?
$this->data['result'] = $this->admincrud->getcategorylist();
$this->data['categoryname'] = $this->admincrud->fetchcategoryname();
$this->load->view($this->layout, $this->data);
}
}
<?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>
<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
I have an issue in image validation using jQuery Or JavaScript.
Please see code below when I tried myself.
Briefing
I want to validate multiple images with the help of for loop.
Issue (Validate Ordering)
When I press submit button this code has validate images in DESC order (see image below) and I want ASC order like 1 field is required... and then 2 field is required etc
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function imageValidation(){
return_var = 'true';
for(var i=1; i<4; i++){
if(($('#player-'+i).val()) == ''){
return_var = i+' field is required';
}
}
alert(return_var);
return false;
}
</script>
<form onsubmit="return imageValidation()">
1 <input type="file" id="player-1" name="players[]" /><br />
2 <input type="file" id="player-2" name="players[]" /><br />
3 <input type="file" id="player-3" name="players[]" /><br />
<input type="submit" />
</form>
image
i have added a new line of code, just break; when first condition match. it will resolve your problem
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function imageValidation(){
return_var = 'true';
for(var i=1; i<4; i++){
if(($('#player-'+i).val()) == ''){
return_var = i+' field is required';
break;// break immediately rather wait to complete the loop.
}
}
alert(return_var);
return false;
}
</script>
<form onsubmit="return imageValidation()">
1 <input type="file" id="player-1" name="players[]" /><br />
2 <input type="file" id="player-2" name="players[]" /><br />
3 <input type="file" id="player-3" name="players[]" /><br />
<input type="submit" />
</form>
According to your code:
function imageValidation(){
return_var = 'true';
for(var i = 1; i < 4; i++){
if(!$.trim( $('#player-'+i).val() )){
return_var = i+' field is required';
break;
}
}
alert(return_var);
return false;
}
But With jQuery
var return_var = 'true';
$('form input[id^=player]').each(function(index, el) {
if(!$.trim( this.value)) {
return_var += (index+1) + ' field is required'; // index is zero based
break; // if you want to stop execution after invalid found
}
});
so your function will look like
function imageValidation(){
var return_var = 'true';
$('form input[id^=player]').each(function(index, el) {
if(!$.trim( this.value)) {
return_var = (index+1) + ' field is required'; // index is zero based
break; // if you want to stop execution after invalid found
}
});
alert(return_var);
return false;
}
I'm new to JavaScript and my form validation works but keeps jumping to validate username on submit even when its validated. Heres my code
function validate_form(form)
{
var complete=false;
if(complete)
{
clear_all();
complete = checkUsernameForLength(form.username.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkaddress(form.country.value);
}
if(complete)
{
clear_all();
complete = checkEmail(form.email.value);
}
if (complete)
{
clear_all();
complete = checkphone(form.phone.value);
}
}
function clear_all()
{
document.getElementById('usernamehint').style.visibility= 'hidden';
/*.basicform.usernamehint.style.backgroundColor='white';*/
document.getElementById("countrthint").style.visibility= 'hidden';
/*document.basicform.countrthint.style.backgroundColor='white';*/
document.getElementById("subhint").style.visibility= 'hidden';
/*document.basicform.subject.style.backgroundColor='white';*/
document.getElementById("phonehint").style.visibility= 'hidden';
/*document.basicform.phone.style.backgroundColor='white';*/
document.getElementById("emailhint").style.visibility= 'hidden';
/*document.basicform.email.style.backgroundColor='white';*/
}
heres the functions
function checkUsernameForLength(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 2) {
fieldset.className = "welldone";
return true;
}
else
{
fieldset.className = "";
return false;
}
}
function checkEmail(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (/^\w+([\.-]?\w+)*#\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(txt))
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
}
else
{
fieldset.className = "";
}
}
function checkphone(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if ( /^((\+\d{1,3}(-| )?\(?\d\)?(-| )?\d{1,5})|(\(?\d{2,6}\)?))(-| )?(\d{3,4})(-| )?(\d{4})(( x| ext)\d{1,5}){0,1}$/.test(txt)) {
fieldset.className = "welldone";
}
else
{
fieldset.className = "FAILS";
}
}
function addLoadEvent(func)
{
var oldonload = window.onload;
if (typeof window.onload != 'function')
{
window.onload = func;
} else {
window.onload = function()
{
oldonload();
func();
}
}
}
function prepareInputsForHints()
{
var inputs = document.getElementsByTagName("input");
for (var i=0; i<inputs.length; i++)
{
inputs[i].onfocus = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "inline";
}
inputs[i].onblur = function ()
{
this.parentNode.getElementsByTagName("span")[0].style.display = "none";
}
}
}
addLoadEvent(prepareInputsForHints);
and heres my form
<form form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" >
<fieldset>
<label for="username">Name:</label>
<input type="text" id="username" onkeyup="checkUsernameForLength(this);" />
<span class="hint" id="usernamehint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="country">Country:</label>
<input type="text" id="country" onkeyup="checkaddress(this);" />
<span class="hint" id="countryhint">This Field Must Not Be Left Blank !</span>
</fieldset>
<fieldset>
<label for="Subject">Subject:</label>
<input type="text" id="subject" onkeyup="checkaddress(this);" />
<span class="hint" id="subhint">Please Indicate What Your Interest Is !</span>
</fieldset>
<fieldset>
<label for="Phone">Phone:</label>
<input type="text" id="Phone" onkeyup="checkphone(this);" />
<span class="hint" id="phonehint">This Feld Must Be Numeric Values Only !</span>
</fieldset>
<fieldset>
<label for="email">Email Address:</label>
<input type="text" id="email" onkeyup="checkEmail(this);" />
<span class="hint" id="emailhint">You can enter your real address without worry - we don't spam!</span>
</fieldset>
<input value="send" type="button" onclick="validate_form(this.form)"/>
<br /><br /> <br /><br />
</form>
Please point amateur coder in right direction Thanks
Like others said, you are trying to access the username inside a condition, where the condition is always false. You set complete=false on start and right after that you try to see if that is true.
By the way, clear_all() may not have the behavior you want before the first validation. It will hide every input in the screen, so if there is anything else wrong, you won't be able to see that. I should go for hiding at the end (or at the beginning like #mplungjan stated, and always depending on what you need), maybe reusing your if(complete) structure:
function validate_form(form)
{
clear_all();
var complete = checkUsernameForLength(form.username.value);
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
}
Also, and after stating the username validation works, you should return a boolean value in the other methods =)
EDIT: Also, checking the errors the others said is a high priority issue.
EDIT2: I turned to see a repeated condition. Now I deleted it. To keep using the if(complete) that way, you should also do these changes:
function checkaddress(whatYouTyped)
{
var fieldset = whatYouTyped.parentNode;
var txt = whatYouTyped.value;
if (txt.length > 3 && txt.length <10)
{
fieldset.className = "welldone";
return true; // <-- this change
}
else
{
fieldset.className = "";
return false; // <-- and this change
}
}
Also, change the other methods to return true and false when you need.
Don't panic.
Everyone has to start somewhere and it can be very frustrating when you're only just learning the ropes.
In answering this question, we need to look not only at your JavaScript, but at the HTML as well.
You don't have a submit input type; instead opting for a regular button. That wouldn't necessarily be a problem, except nowhere in your JavaScript are you actually submitting your form. That means every time someone clicks the "Send" button, it will fire the validate_form() function you've defined but do nothing further with it. Let's make a couple of changes:
Replace your button with a submit input:
<input value="send" type="submit" />
Next, add the following code to your form tag so that we define an action to take when the user tries to submit your form:
onsubmit="validate_form(this)"
So your whole form tag now looks like this:
<form method="post" action="mailto:s00103684#mail.itsligo.ie" name="basicform" id="basicform" onsubmit="return validate_form(this)">
Notice I removed an extra "form" from that element.
Ok, next we want to handle what happens when the form is ready to be validated.
function validate_form(form)
{
// ...we can step through each item by name and validate its value.
var username = checkUsernameForLength(form["username"].value);
var email = checkaddress(form["country"].value);
// ...and so on.
return (username && email && {my other return values});
}
Each method you call (e.g. CheckUsernameForLength) should return either true or false, depending on whether the input is valid or not.
Our last return is probably a little inelegant, but is a verbose example of a way to aggregate our returned values and see if there are any "failed" values in there. If all your methods returned true, that last return will evaluate to true. Otherwise (obviously) it will return false.
The submission of the form will depend on whatever value is returned from your validate_form() function.
Please start with this ( http://jsfiddle.net/4aynr/4/ )
function validate_form(form)
{
var complete=false;
clear_all();
complete = checkUsernameForLength(form.username); // pass the FIELD here
if(complete)
{
complete = checkaddress(form.country.value);
}
if(complete)
{
complete = checkEmail(form.email.value);
}
if (complete)
{
complete = checkphone(form.phone.value);
}
if (!complete) alert('something went wrong')
return complete;
}
and change
<form form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform" >
to
<form method="post" action="mailto:s00103684#mail.itsligo.ie"
name="basicform" id="basicform"
onSubmit="return validate_form(this)">
and change
<input value="send" type="button" onclick="validate_form(this.form)"/>
to
<input value="send" type="submit" />