select last visible field when function is used [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
This is my problem:
We have 5 input fields with the same class name, for example class="inputfield". By default, when the page is loaded, you only see the first. Next to the field you have a button to show the second field. When you click on it, the function showNext() is used and you will see the second field with next to it again a button to show the 3rd field etc...
What do I want to do? I have to get the last visible input field with class="inputfield".
I've already found the function last() and :visible, but when I click on the button to show the next input field, the first is still the last because I don't know how to refresh my code.
What I want to do is, every time the function showNext is called, I need to run my code so I alway have the last visible input field. I can't add code in showNext() so I need a listener and my own code to select the last visible input field.
With my code I want to add a value in the input field when the user clicks on another button that I will display. But I always need to add it to the last visible input field, that's why I need to know what the last visible field is...
Extra info:
The non visible fields are already in the code with display:none.
What I tried is:
when I only use the $(".inputfield").last() I get the last field, but the invisible one...
with $(".inputfield:visible") it's always the first that is "selected". Even if the second is now visible
Is this possible?
Printscreen of my problem:
I select it with
$(".inputfield:visible").last().css("border", "2px solid #990000");
Edit:
I think I found a way around for my problem so I always have the last visible field. Tnx for the help.

To get the last element with classname 'inputfield':
var inputs = document.getElementsByClassName('inputfield');
var lastInput = inputs[inputs.length - 1];
To get the last visible element with classname 'inputfield', it's easier to use jQuery:
var inputs = $('.inputfield:visible').last();

Your question isin't that clear, but from what I understand, you are trying to access the last element that was visible after showNext is called.
Knowing that the last visible input is the input that precedes the currenlty visible one, you could use that logic to know what was the last visible input once showNext is called.
However, you can also simply retrieve the currently visible element before calling on showNext.
var $lastVisible = $('.inputfield:visible').last();
showNext();
Note that you can also use the same logic to get the last field that was made visible after showNext was called if you inverse the statements.

Related

Why is the alert, within an if statement, not closing when I click ok?

I'm programming a learner test, using checkboxes. Functional requirements, per the client, are that the learner must score 100% to pass. The learner gets 3 attempts to pass and then must start the course over at the beginning. After each of the first 2 wrong selections, the learner is sent back to the first question of the test; "#vidQ1".
So far, I have a 'wrong answer' alert that tells the user that they made a wrong selection and how many attempts they have left. This is done as soon as the user makes a wrong selection. It doesn't wait for a submit event. The alert is correctly displaying the message and the decremented 'attempt' variable value and is also logging the new attempt value to the console.
The problem is that the alert does not close when the 'OK' button is clicked. But the 'attempt' variable is decremented each time the 'OK' button is clicked and the new value is logged to the console. I can only close it by closing the entire window. So the function is stopping at the alert, and I don't know why.
var attempt = 3;
...
$('#ques01_b').click(function() {
if( $(this).is(':checked')) {
attempt --;
console.log(attempt);
alert("That is incorrect. You have this many attempts left: " +attempt);}
$("#vidQ01").focus();
});
JS Fiddle: https://jsfiddle.net/frankmix/h86n93bx/38/
Description:
The javascript in the Fiddle is a portion of the 'loadvideos.js' file I created and the checkbox icon manipulation used for custom check marks.
The JavaScript in the Fiddle is for the loading and playing back of ONE of total of 30 questions and accompanying video simulations, each with 3 checkboxed responses to choose from, into a single div (#vidContainer).
I recently added the var attempt = 3 (today).
When the correct checkbox is selected, the video simulation plays. When the video ends, the first question and possible answers fadeout and the next question and possible answers fades in, and when the learner selects the correct answer for the next question, the first video displays none, and the next video loads and plays, and so on, for 30 videos.
Each question is in its own fieldset, and each fieldset contains 3 checkbox containers div's, for the 3 choices, that allow for the custom checks (green checks for correct selections and red x's for wrong ones).
There is only the first question here. The correct response is A (the checkbox input id="ques01_a")
Below the function that fires when the correct selection is made is my initial attempt at handling a wrong choice' B, in this case (the checkbox input id="ques01_b")
Below that is the checkbox icon manipulation code for the first question
Everything works and is 508 compliant as well to this point.
I'm now trying to add functions for counting and handling wrong answers; starting at LINE 20 in the JS part of this fiddle. That is where I'm asking for your help at.
Sorry this is so wordy. I wanted to spare you all of that :)
Thanks again.

How can I keep the focus on an input field if the input is incorrect

Given the following code:
sPosSelect="#fpJpos input[name=posnum" + iiPos + "]";
if (fIn>fPosMaxWtUse[iiPos]) {
alert(sprintf('%.0f is %.0f more than the position max of %.0f.',fIn,fIn-fPosMaxWtUse[iiPos],fPosMaxWtUse[iiPos]));
$(sPosSelect).val('');
$(sPosSelect).focus();
return;
}
It works in that I get the alert, and the field is blanked. However, the focus then moves on to the next field when what I want is for it to stay on the field just blanked so the user can try again.
All suggestions are welcome, including anything I'm doing that could be done in a better way.
Terry
I assume your code is within an event attached to the field in question, presumably on blur?
If this is the case, you should simply use return false at the end of the function. This will tell the browser to ignore it's default behaviour, which in this case would be moving to the next field.
What your code is doing at the moment is setting focus in the field, and then returning control to the browser, which assumes everything went okay, and happily moves on to the next field.
Also, if this code is within an event attached to the field, you should really be using $(this) in place of repeating the selector $(sPosSelect).

Running function only if a certain element isn't burring

im making an application that creates a text input where ever you click. I was having a problem where whenever you would click inside the field another text field would appear but i managed to fix that. I have one last major issue that I just can't solve. I know ou can't use blur() and focus() as arguments (though it would be nice) but i need to find a way so that after you enter text into the input field and out click, it just blurs the input box and doesn't create another until the user clicks again.
Just create a variable to keep track or only use a certain ID for the input you create, then check for that variable or input element before creation..
if(!$("#myDynamicInputElement").length){
//TODO: Create your element..
}

How to prevent multiple html selection box displayed on screen?

I have been working on the last bit of my php + ajax based datagrid project.Everything works as I designed except one thing : I cannot stop user opening multiple selection boxes...
Go my research page and use username "ChenxiMao" and password "accedo" to login(without double quotes).
Note that perhaps the images used in this datagrid would not be displayed when page is loaded for the first time(weird, I am trying to fix this, browser incompatibilities, perhaps).
If you double click on one cell in the "CONSULTANT" column, a html select box would be displayed, you can select one consultant to assign him to this task or unassign the consultant from this task. No problem for this.
The problem is : when user leaves this selection box OPEN, he/she can still open another selection box... My jquery code cannot stop people from opening multiple selection boxes.
You can ctrl-U to see the source code on this page, and check the content inside the "gridview-helper.js" for what I have been done.
I want to let user only open a single selection box. When he/she leaves the cell, the selection box should be closed, without changing the html inside...
Puzzled, screwed up for this afternoon...
Thanks for any suggestons in advance!
JavaScript is single-threaded, so you can add a mutex variable and check its value before opening a new select box.
At the top of gridview-helper.js:
var is_choice_visible = false;
In your double-click handler:
$(this).dblclick(function()
{
if (is_choice_visible)
return;
is_choice_visible = true;
...
For your select box, add an onblur handler which sets is_choice_visible back to false and deletes itself.
Unrelated tip: Growing a string in a loop is slow on older versions of Internet Explorer. It's more efficient to append to an array and join the array, e.g.:
var html = ["<select>..."];
for (var i in consultantnames)
{
html.push("<option>...</option>");
}
html.push("</select>");
return html.join("");
Have you tried using the onmouseout event on the cell, and removing the child dropdown box element if mouse out is triggered? Seems that should work.

Dynamically growing an array of text inputs (HTML/JavaScript)

I'm creating a data entry app for some in-house stuff.
My team needs to enter info about "items" which can have many "categories" and vice versa.
I need a quick way to let them enter an arbitrary amount of categories.
Here's my idea:
On the item entry page, I'll have it so that initially there's one text input for "categories" and if it's tabbed out of while it's empty, the input field is deleted (unless it's the only one) and focus skips to the next field. If it's not empty when it's tabbed out of and if it's the last input field in the array, then an additional "category" text input will be added and focused.
This way people can enter an arbitrary amount of categories really quickly, without taking their hands off the keyboard, just by typing and hitting tab. Then hitting tab twice to denote the end of the list.
First of all, what do you think of this interface? Is there a better way to do it?
Second of all, is there a jQuery (or something) plugin to do this? I've searched but can't find one. I searched scriptaculous/prototype and mootools too, with no luck.
I would obviously rather use something tried and tested than roll my own.
Any and all advice appreciated
First I'll try to address the problems commented on nickf solution.
To set the focus on the newly created input $copy.find(":text").focus(); will not work. The jQuery focus method only triggers the event, but does not call the underlying focus method.
You can set the focus with setTimeout(function(){$copy.find(":text").get(0).focus()}, 10); but:
setTimeout is needed in firefox or strange things will happen with the blinking cursor.
IE7 needs another input to focus when tabbing. I haven't found the way to set the focus on an input if the focus goes to the address bar. I suppose this will not be a problem because you will need at least a submit button.
To control shift-tab I've been trying to track the focused element, in order to skip the blurHandler when the focused element is a previous input, but the resulting code is really ugly so I'll post this and look for a better solution.
And last, you're asking what we think of this UI, and I think that a comma separated list of categories is easier to code an to fill in. :-)
it's actually not too difficult to implement that, even with vanilla JS (ie: no jQuery, prototype, etc), but everything is easier with jQuery, so I'll have a go at it using that:
Assuming a structure like this:
<form id="myForm">
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
<div class="inputRow">
<input type="text" name="myInput[]" />
</div>
...
</form>
Here's the JS
$('#myForm :text').blur(onBlurHandler);
function onBlurHandler() {
$row = $(this).parent();
if ($row
.nextAll(":has(:text)") // all following divs with a text element
.length == 0 // but there aren't any, we're on the last one
) {
if ($.trim($row.find(":text").val())) { // the text box isn't empty
$copy = $row.clone(true);
$copy
.find(":text") // get the new text box,
.val('') // remove any text in it
.blur(onBlurHandler) // and add the event handler (is this necessary?)
;
$copy.insertAfter($row);
} else if ($row.prev(':has(:text)').length) { // the text box is empty, and this one isn't the first row
$row.remove(); // get rid of the row.
}
}
}
Response to comments:
thanks for the answer! i've tried it but it doesn't seem to work as intended. i'm on mac firefox. if i tab off the last field, it adds the new one but focuses the address bar. i tried adding: $copy.find(":text").focus(); after the insertAfter line, but it doesn't change anything. any ideas?
also if i shift-tab the blurhandler doesn't know i'm going in the opposite direction. is there any way around that?
Hmm, I hadn't thought about that. What you could try doing is to put an element after all your text fields which can take focus (like a textbox which is rendered off-screen, eg: margin-left: -10000px). Add an onfocus handler onto that to see if the last row is empty, and if it is, then it would have been added just then by the onBlurHandler function, so pass the focus back to the last row. If the last row isn't empty, then pass the focus onto the next element (your submit button, probably). If there are issues with the last row not existing in the DOM yet, then put the above into a timeout.
(If this actually works) this should let your users tab backwards and forwards without hassle.

Categories