Welcome Guest, Not a member yet? Register   Sign In
using jquery on checking duplicate data in database with dynamic textfields
#1

[eluser]clariz[/eluser]
Could anyone help me on this?

I have dynamic textfields, generated using innerhtml
I want that onblur event, the data in the textfield will be checked for duplicate in the database. The checking will be done without refreshing the page.
Then give an alert if duplicate exists.

I have a code using jquery. I've tried it using static textbox. It works fine.
But when I applied the dynamic textboxes, it doesn't works.

Here's my code:
I have a javascript code and two forms in my html code.
The code goes like this, when I enter a value in my textfield id = Que and on onblur event, the next textfield id = textQuestion gets the value of the textfield id = Que and the form id=formCheck submits the form. The data is process to a php file, checking if the value exists in the database. Then returns a value.


Code:
< script type="text/javascript">
    $(document).ready(function(){
        $('#Que').blur(function(){
            $('#txtQuestion').attr('value', $('#Que').attr('value'));
            $('#formCheck').submit();
        });
                $('#formCheck').ajaxForm({success:show_result});
                });        
                function show_result(responseText){
                        var arr = responseText.split('###');
                        if(arr[0] > 0){
                                alert("Error: Question already exists.");
                        }
                }

< /script>
&lt;form name="formCheck" method="post" id="formCheck" action="&lt;?= site_url("lessons/main/checking");?&gt;"&gt;
        &lt;input type="text" name="txtQuestion" id="txtQuestion" /&gt;
&lt;/form&gt;

&lt;form method="POST" name='formQ' id='formQ' action='&lt;?= site_url("lessons/main/saveAll");?&gt;'&gt;
   <div>
        Question &lt;input type='text' name='Que[]' id='Que' size='38' /&gt;
   </div>
   <div><a href='[removed]addQue()'>add another question</a></div> // this the call to generate dynamic textfields
   <div><span id='newQuestion'></span></div>     // here is where dynamic textfield takes place
&lt;/form&gt;

This is my controller:
It checks the value in the database

Code:
&lt;?php
  class Main extends Controller{
      
      function __construct(){
        parent::Controller();
      }

      function checking(){
        $sql = "Select * from lesson_questions where UCASE(question) = '".strtoupper($_POST['txtQuestion'])."'";
        $qry = mysql_query($sql);
        
            echo mysql_num_rows($qry) . '###';
      }

}
?&gt;


And this is the code to generate dynamic textboxes


Code:
var arrInput = new Array(0);
  var arrInputValue = new Array(0);

function addQue(){
  arrInput.push(arrInput.length);
  arrInputValue.push("");
  displayQue();
}

function displayQue() {
  document.getElementById('newQuestion'). innerHTML="";
  for (intI=0;intI<arrInput.length;intI++) {
    document.getElementById('newQuestion'). innerHTML+=createQue(arrInput[intI], arrInputValue[intI]);
  }
}

function saveQue(intId,strValue) {
  arrInputValue[intId]=strValue;
}

function createQue(id,value) {
  return "Question &lt;input type='text' name='Que[]' id='Que' size='38'&gt;";
}

Please anyone help me on this.
I am new to jquery. Any reply is very appreciated.


-clariz-
#2

[eluser]GSV Sleeper Service[/eluser]
Although using innerHTML is quick and easy, jquery has problems attaching events to these new elements. You should be using the jquery DOM manipulation methods instead - http://docs.jquery.com/Manipulation
#3

[eluser]clariz[/eluser]
Thanks for the reply GSV...
I would try that one too.

Based on my experiments, research and tests, the problem I have here is that
the code
$('#Que').blur(function(){
only searches for a single id Que. When I generate another textbox, an array of id Que is generated.
The code only looks for the first id Que and leave the other ids.
Could you help me solve the problem..
Now I'm finding a code that when onblur event in an array of textbox, the code will determine on which textbox the event last happened, get the value of the textbox and place to the textbox id = txtQuestion.

Could you help me with this?
Thanks in advance.

-clariz-
#4

[eluser]GSV Sleeper Service[/eluser]
ID's should be unique, maybe you should use a class instead of an ID for these elements?
#5

[eluser]clariz[/eluser]
Thanks GSV...

But I don't know how to use class. Since I am new to jquery.
Could you give me some example to use class in my problem?

Thanks a lot...

-clariz-
#6

[eluser]Vitek[/eluser]
Hi clariz,

A couple of points to answer some of your other questions:

1. The reason blur() was only being applied to the first #Que element was because you were not binding blur() to the other #Que elements as they were being created. jQuery will only bind functions to elements that exist at the point blur() is invoked.

2. When using classes you use CSS class notation: $('.class')

Onto the JS:

Code:
$(function() {
     //NOTE: Edited in line with the posts below
     //This function sets the value of #txtQuestion and submits the form via Ajax
     function checkQuestion() {

        $('#txtQuestion').val($(this).val());
                
        $('#formCheck').ajaxSubmit({

            success :  function(response) {                  
                if (response > 0) {
                    alert('Question already exists!');
                }                  
            }

        });
    }

    //Bind checkQuestion() to the blur event of ALL input fields
    //$(this).val() grabs the value of the relevant textbox
    $('#Questions > input').bind('blur', checkQuestion);
    
    $('#addQuestion').click(function() {

        //Append a new textbox to our #Questions DIV
        $('#Questions').append('&lt;input type="text" name="Que[]" size="38"&gt;');
        
        //Bind checkQuestion() to the updated collection of textboxes that we have
        $('#Questions > input').bind('blur', checkQuestion);
        
        return false;
    
    });

});

Code:
&lt;form name="formCheck" method="post" id="formCheck" action="&lt;?= site_url("lessons/main/checking");?&gt;"&gt;

    &lt;input type="text" name="txtQuestion" id="txtQuestion" /&gt;

&lt;/form&gt;

&lt;form method="POST" name='formQ' id='formQ' action='&lt;?= site_url("lessons/main/saveAll");?&gt;'&gt;

    <div>
        <a href="" id="addQuestion">Add another question</a>
    </div>

    <div id="Questions">
        Question &lt;input type='text' name="Que[]" size='38' /&gt;
    </div>

&lt;/form&gt;

The above code assumes a couple of things:

1. You are indeed using the jQueryForm plugin (which I assumed by your use of ajaxForm())
2. Main::checking() returns just the row count, without the '###'
3. #newQuestion has been replaced by #Questions. This is where ALL textboxes will go - both the static one and any that are created dynamically

I've tried to stay as close to your approach as possible. I hope it does the job for you (I should mention it's untested as well, it's 5am :-P )
#7

[eluser]clariz[/eluser]
[quote author="Vitek" date="1221987748"]Hi clariz,

A couple of points to answer some of your other questions:

1. The reason blur() was only being applied to the first #Que element was because you were not binding blur() to the other #Que elements as they were being created. jQuery will only bind functions to elements that exist at the point blur() is invoked.

2. When using classes you use CSS class notation: $('.class')


The above code assumes a couple of things:

1. You are indeed using the jQueryForm plugin (which I assumed by your use of ajaxForm())
2. Main::checking() returns just the row count, without the '###'
3. #newQuestion has been replaced by #Questions. This is where ALL textboxes will go - both the static one and any that are created dynamically

I've tried to stay as close to your approach as possible. I hope it does the job for you (I should mention it's untested as well, it's 5am :-P )[/quote]


Thank you Vitek...
Yes, I am using jQueryForm plugin..
I'll just post with regards to the status of my problem. As of now, I'm testing different ways to solve it.
I'm really excited to use the code you have given. :cheese:

Thanks a lot. :-)


EDIT:
I have just tested the code but nothing happens on the event blur. I don't know what is the error behind.


-clariz-
#8

[eluser]Vitek[/eluser]
Hi again, clariz,

Looks like my tiredness kicked in after all! The problem is that I used blur() to bind a named function to each textbox, when in fact blur() only takes anonymous functions. You just need to make this small change:

Code:
function checkQuestion() {
    
    $('#txtQuestion').val($(this).val());
                    
    $('#formCheck').ajaxSubmit({
    
        success :  function(response) {                  
            if (response > 0) {
                alert('Question already exists!');
            }                  
        }
    
    });
}

Then replace both blur() calls from the original code with the following line:

Code:
$('#Questions > input').bind('blur', checkQuestion);

I got paranoid and just tested it all and it works fine for me. Let me know how it works for you.
#9

[eluser]clariz[/eluser]
Thanks Vitek.
I have tried your code but the same thing happened, the problem still there.
But thanks for that code, that helps.Really gave me new ideas.

I came up to a code which solved the problem.
I also used Vitek's code as a reference, and also GSV Sleeper Service's idea.
At the end, the code I made was not that good but it solved the problem which is more important (to have an output) :lol:

JS code in a separate file:
Code:
function clickHandlers(e){
  stat = 'False';
  $("input.inputQuestion").blur(function(){
    $("#txtQuestion").attr("value", $(this).attr("value"));
        $("#formCheck").ajaxSubmit({success:show_result});
   });
}
    
function show_result(responseText){
  var arr = responseText.split('###');
  if(arr[0] > 0){
      if(stat == 'True'){  
         return false;     //this is to prevent alert function from
                           //"popping up" twice or more in same question value
                           //since I have a hard time understanding the code of event delegation in jquery
      }
  alert("Error: Question already exists.");
  stat = 'True';
  }
}

Same html code except this line
Code:
Question &lt;input type='text' name='Que[]' id='Que' size='38' /&gt;

I changed it to
Code:
Question &lt; input type='text' name='Que[]' id='Que' on blur = ' clickHandlers ( ) ' class='inputQuestion' size='38' &gt;

And also in creating dynamic textfields was changed to
Code:
Question &lt;input name='Que[]' type='text' class='inputQuestion' id='Que' value='"+ value +"' size='38' on blur= 'clickHandlers()' on Change ='[removed]saveQue("+ id +",this.value)' /&gt;


I just added a call to a function.

I hope anyone could find this post useful.
Thanks for the persons who read this post especially to Vitek, and GSV Sleeper Service for all the replies. Really appreciate you guys. ;-)


-clariz-




Theme © iAndrew 2016 - Forum software by © MyBB