Jump to content
ajoo

collecting user inputs sequentially

Recommended Posts

Hi, 

I need to collect user inputs in input boxes. All boxes are disabled except the one which awaits input. once an input is made and satisfies a certain criteria, the next input box in the sequence is enabled and awaits input. 

Thus i need my code to cycle a certain section of my code and collect all inputs which is like saying it needs to do nothing as it waits for the user input. I cannot put this in any loop because it freezes the loop. The only way I can think of accomplishing this is by using a setTimeout and awaiting for keypress during that time, collecting input, breaking out of the loop, and targetting the next inputbox in the setTimeout function till all input is collected. I just wish to know if anyone has a better idea to do this task.

Thanks !

Share this post


Link to post
Share on other sites

Have you tried connecting event listeners to your input fields? When the event is triggered, you run whatever test is needed to determine whether the next input field should be enabled.

Based on one of your previous posts, I'm guessing that you're using jQuery. More information about the different types of listeners in jQuery can be found here:
https://api.jquery.com/category/events/

Share this post


Link to post
Share on other sites

There shouldn't be any need for timeout loops. In this example, my "certain criteria" is that an input must have an even value

    <form>
        <fieldset><legend>User Inputs</legend>
            A <input type="number" name="field_a" value="1" data-seq="1"  class="my_input" autofocus><br>
            B <input type="number" name="field_b" value="3" data-seq="2"  class="my_input" disabled><br>
            C <input type="number" name="field_c" value="5" data-seq="3"  class="my_input" disabled><br>
        </fieldset>
        <br>
        <input type="submit" name="btnSubmit" value="Submit">
    </form>

JS code

<script type="text/javascript">
    $().ready( function() {
        
        $(".my_input").change( function() {
            var seq = $(this).data("seq")
            // ensure input is even and non-zero
            if ($(this).val() > 0 && $(this).val()%2==0) {
                ++seq
                var nextinput = $(".my_input[data-seq="+seq+"]")
                alert( $(nextinput).val() )
                $(nextinput).prop("disabled",false)
                $(nextinput).focus()
            }
            else {
                $(this).focus()
            }
        })
    })
</script>

 

Share this post


Link to post
Share on other sites
Posted (edited)

Hi,

@cyberRoot : Thanks for the response. Yes I am / was using the keypress event.  

@Guru Barand: 

My code at the juncture I put this question was as below:

	
// 	each input element has a unique id = 'result_1', 'result_2' and so on.
		m=1;		
		myResult = $('#result_'+m);

		ansUp = ['5','11','18','26'...];
		
		$('input[type=text]').prop("disabled", true);
//		console.log(myResult);		
		myResult.prop('disabled',false);
		myResult.val(0);
		myResult.select();
		myResult.addClass('yellow');	

	while(m < 9){
		
		myResult.keypress(function(e) {
			if (e.keyCode === 13) {
				myval = myResult.val(); 
				if(myval == ansUp[m-1])
				{
					myResult.addClass('green');
					myResult.prop('disabled',true);
					m++;
					myResult = $('#result_'+m);
					myResult.prop('disabled',false);
					myResult.addClass('yellow');					
					myResult.val(0);
					myResult.select();
					return true;
				}
				else {
					myResult.addClass('red');
					myResult.select();
					return false;
				}	
			}	
		})

	}	

I thought the while loop would work but then obviously that was incorrect. So i removed the while loop and thought I should add 

myResult.keypress(function(e) {.... }  // just before return true.

but that made it cyclic and that too was not great. I was missing the idea of a common class changing event which you were kind enough to show me in your code. 

Now I have it working for the most, the only issue is that the enter key needs to be pressed twice before the event is registered which is very odd.  Here is the final code which needs me to press the enter key twice.  I suspect it has something to do with the '0' value that I put into the input box and then put the focus on that for the ease of the user. 

Here's how it stands now:

	$(".ui").change(function(){
		myResult.keypress(function(e) {
			if (e.keyCode === 13) {
				myval = myResult.val(); 
		
				if(myval == ansUp[m-1])
				{
					if(myResult.hasClass('red')){
						myResult.removeClass('red');
					}
					myResult.addClass('green');
					myResult.prop('disabled',true);
					m++;
					myResult = $('#result_'+m);
					myResult.prop('disabled',false);
					myResult.addClass('yellow');					
					myResult.val(0);
					myResult.select();
				}
				else {
					myResult.addClass('red');
					myResult.select();
				}	
			}	
		})
	})	

Please help !

Thanks loads Guru Barand and cyberRoot !

Edited by ajoo

Share this post


Link to post
Share on other sites

OK, I managed to rectify it though i still do not understand why it's fixed by using keyup event handler in place of keypress. keydown also gives the same problem as keypress. 

It would be great if  you can explain it.

Thanks !

Share this post


Link to post
Share on other sites

Hi !

I have a working fiddle here https://jsfiddle.net/zswrd5oh/

While it works great for the 1st pass, (a table of 2 - 1st 9 even values )  the 2nd pass, though it works through it and gives the wanted result ( table of 3), is still flawed, in that it generated extra return key codes thereby upsetting the code logic and generating error conditions ( red boxes).

I know its a bit difficult to explain but can easily be figured if the fiddle is run twice using the ready button. I have set alerts which are different in the 2 cases. Also if run in the browser, the console.log shows how the keys are registered by the program differently in the 2 passes. 

Ideally it would be best if the 2nd pass runs just like the first pass did.

Would be grateful for any help to resolve this. 

Thanks !   

Share this post


Link to post
Share on other sites

Your problem is that you're adding extra keyup handlers each time a field changes.  Look at your code:

$(".ui").change(function(){
	myResult.keyup(function(e) {
		//...
	});
});

That says, every time an element in .ui changes, add a keyup handler to myResult. 

So on your first pass, as you enter your inputs you're adding a key up handler to every input.

On your second pass, you end up adding yet another key up handler to every input so your handler function ends up running twice.

On a third pass, you'd add another so your handler runs three times.

...

Combine that with your global state variables and you get a mess.  When you enter the right value your first handler changes myResult and m to a different input.  Then your second handler looks at that new input value and sees that it doesn't match the next sequence value and shows an error.

You need to remove the change handler and just add a single keyup (or keypress) handler.  Ideally you'd find a way to rely on global state variables less as well.

 

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.