Javascript: How to make this function working for click effects - javascript

I am designing a page where it displays the staff details in following structure :
user can click anywhere in the details box and the checkbox will get selected along with the change in the className of the details <div> box.
The problem i m facing is when i click anywhere in the details box it works fine.. but when i click on checkbox it only changes the className but doesnt make any changes to checkbox.
Also there is one condition, few users are allowed to selected limited staff at a time and few are allowed to select all of them..
I have assigned a myClick() function to the outer <div> box (one with red border)
and the function is :
var selectedCount = 0;
myClick = function(myObj,event)
{
var trgt =(event.srcElement) ? event.srcElement : event.target;
tgName = trgt.tagName;
//following statement gives me correct details element event though i clicked on any child tags
theElem = (tgName == 'DIV') ? trgt : ( (tgName == 'B') ? trgt.parentNode.parentNode : trgt.parentNode);
if(allowed_selection == 'unlimited')
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
}
else if(theElem.className == 'details_hover')
{
theElem.className = 'details_clicked';
if(tgName != 'INPUT') theElem.getElementsByTagName('input')[0].checked = true;
}
}
else
{
if(theElem.className == 'details_clicked')
{
theElem.className = 'details';
theElem.getElementsByTagName('input')[0].checked = false;
selectedCount--;
}
else if(theElem.className == 'details_hover')
{
if(selectedCount == allowed_selection ) return false;
theElem.className = 'details_clicked';
//i think, this is the suspicious area for errors
theElem.getElementsByTagName('input')[0].checked = true;
selectedCount++;
}
}
return false;
};

The problem is these return lines in your function:
return false;
When you connect an event to a form element that performs an action, such as a checkbox or button, returning false will prevent that default action. It stops the event from taking place as it regularly would.
You could try something like this at the top of your function:
var returnValue = (tgName == 'INPUT' && trgt.type == "checkbox") ? true : false;
And then when calling 'return ', use:
return returnValue;
If you return true you allow the checkbox to act as normal and check / uncheck itself.

Related

Select different word each time TAB key is pressed

Move across each word in a sentences.
I have created shortcut key for enter in my application as, it will move towards and focus each input control in my page.
I need to set keyboard shortcuts for tab as, it has to select each string of a sentences which are in some textbox. For example txtAddress contain value like "Hi i am new user", if I press tab key it has to select a string "hi" then "i" then "am" then "new" then "user" after that it has to focus a next input control.
I have tried with following JS to focus next input control but don't know how to select each word in textbox.
$(document).unbind('keydown');
$(document).bind('keydown', 'tab', function assets() {
try {
var inputs = $(":input:not(input[type='hidden'])");
var CurInput = inputs.get(inputs.index(document.activeElement));
var nextInput = inputs.get(inputs.index(document.activeElement) + 1);
if (CurInput && nextInput.type == "text" && CurInput.style.display != "none") {
var strval = CurInput.value;
if (!strval) {
if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
}
}
else if (nextInput && nextInput.type != "hidden" && nextInput.style.display != "none") {
nextInput.focus();
}
return false;
}
catch (e) {
}
});
http://jsbin.com/cihahigevo/1/edit?html,js,output
var textarea = $('textarea')[0],
index = 0;
$(document).on('keydown.tab', function(e){
if( e.keyCode == 9 ){
textarea.focus();
textarea.value = textarea.value.trim() + ' ';
index = textarea.value.indexOf(' ', index) + 1;
textarea.setSelectionRange(0, index);
}
return false;
});
It's never a good idea to override a users keyboard, especially the tab button.
The tab button is used by people who (for whatever reason) don't use a mouse to navigate sites by 'tabbing' between buttons, form fields, etc.
If you remove this functionality by overriding the tab key, you've suddenly made your site unaccessible to these users.
You may also run afoul of you countries laws on website accessibility (the Disability & Discrimation act in the UK).

How to tell if a radio button is left unchecked with Javascript/JQuery

I am creating a quiz/survey form with jQuery and javascript and I am having some trouble with the question validation.
The way the quiz/survey creation works is a series of show/hides display relevant form fields. The user fills out one set of fields for the first question and then they are asked if they would like to add another question to their quiz/survey and the next set of form fields is displayed.
I am struggling because instead of having a massive validation when the user has completed all of their possible form fields I am running a validation script at the end of each question with the associated form field IDs and values being passed into the script upon the user completing that question. This script is below, but some key areas of the script are based upon whether radio buttons have been checked. For instance if the user has left the question text area empty they are alerted to fill in question text, or if they select a true/false answer or multiple choice answer, they are supposed to determine which is the correct answer based upon a radio button list. Here is the entire validation code:
var questionValidate = function(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID) {
// alert(qTextID, qAnswerType, TFID, MCID, MCText1, MCText2, MCText3, MCText4, VisRef, Youtube, Vimeo, ImgID);
if (jQuery('select[name="CAT_Custom_14"]').val() == 'Quiz') {
if (jQuery(qTextID).val() == "") {
var qText = true;
alert('Question Text field is blank!');
};
if (jQuery(qAnswerType).val() == " ") {
var answertype = true;
alert("There's no answer selected.");
} else if (jQuery(qAnswerType).val() == 'True/False') {
if (jQuery(TFID).attr("checked") == true) {
var tfanswer = true;
var mcanswer = false;
alert('True False is selected');
} else if (jQuery(TFID).attr("checked") == false) {
alert('True False is not selected.');
};
} else if (jQuery(MCID).attr("checked") != 'checked' ) {
var mcanswer = true;
var tfanswer = false;
alert('The correct Multiple Choice Answer is not selected');
if (jQuery(MCText1).val() == "" || jQuery(MCText2).val() == "" || jQuery(MCText3).val() == "" || jQuery(MCText4).val() == "") {
var mcTextfields = true;
alert("There are Multiple Choice Fields that you have left blank.");
} else {
mcTextfields = false;
};
};
if (jQuery(VisRef).val() != " ") {
if (jQuery(VisRef).val() == "Youtube Video" && jQuery(Youtube).val() == "") {
youtubeVal = true;
alert('Please enter your Youtube Video code.');
} else if (jQuery(VisRef).val() == "Vimeo Video" && jQuery(Vimeo).val() == "") {
vimeoVal = true;
alert('Please enter your Vimeo Video code.');
} else {
validateImage(ImgID);
};
} else {
youtubeVal = false;
vimeoVal = false;
tempImgCheck = false;
}
};
};
I have run into a way to tell whether the radio button is checked, however it does not appear to be working with my script the way that I want it to. If you look at this area of the code you should be able to see that it first determines the answer type (true/false or multiple choice) and then if the correct answer is not selected the user should be alerted. So if they do not select the 'true', 'false', 'a', 'b', 'c', or 'd' radio button the validation should alert them to select it.
If there are any other ways to check if the correct radio buttons are selected I would appreciate anyone's help in figuring this out.
Thank you so much!
I think you want something like this:
if($('#radio_button').is(':checked')){
alert("I am checked");
}
You could check for a button that isn't checked by negating that statement.
if(!$('#radio_button').is(':checked')){
alert("I'm not checked");
}

Validate multiple textboxes

I have this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});

Javascript or jQuery form validation only for exact action

I have a form with several action buttons, and every button has a different action.
For example, one button is "Save and continue" and another is "Save and finished". I want to validate values from selections on the form, and if the value is equаl to some number, only then can it run the action "finished". I want to validate only for this exact action.
I try this but it did not work:
function OnSubmitForm() {
if(document.pressed == 'SOME ACTION') {
var x=document.forms["FORM NAME"]["INPUT NAME"].value;
var i="";
if (x==null || x!=i) {
alert("You can't do this");
return false;
}
}
else
return true;
}
My idea is to validate only when clicking on the exact action on the form.
Hmm, I have an idea. Why don't you listen for the change event on your <select> element and update the buttons disabled attribute, like so.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = null;
if( value === 1 ) {
disabled = true;
} else if( value === 2 ) {
disabled = false;
}
$('#theButton').prop('disabled', disabled);
});
Or if you want to do it the nerdy way you could do this.
$('#mySelectBox').change(function() {
var value = this.value,
disabled = value === 1 ? true : false;
$('#theButton').prop('disabled', disabled);
});
That should work, hope it helps.

jJavascript select box hanging on second select in IE7

I have a drop down select box inside a div. When the user clicks on change, a dropdown box appears next to the change/submit button and the user makes a selection which then updates the database and the selection appears instead of the dropdown. All works fine in IE8 and Firefox but in IE7 it allows one selection (there are several identical dropdowns) but the second time a selection is made it hangs on "please wait". This is the relevant code:
<td width=200>
<input type="button" onclick="startChanging(this)" value="Change" /></td>
<script type="text/javascript">
var selectBox, isEditing = false;
var recordvalue;
if( window.XMLHttpRequest ) {
recordvalue = new XMLHttpRequest();
} else if( window.ActiveXObject ) {
try {
recordvalue = new ActiveXObject('Microsoft.XMLHTTP');
} catch(e) {}
}
window.onload = function () {
selectBox = document.getElementById('changer');
selectBox.id = '';
selectBox.parentNode.removeChild(selectBox);
};
function startChanging(whatButton) {
if( isEditing && isEditing != whatButton ) { return; } //no editing of other entries
if( isEditing == whatButton ) { changeSelect(whatButton); return; } //this time, act as "submit"
isEditing = whatButton;
whatButton.value = 'Submit';
var theRow = whatButton.parentNode.parentNode;
var stateCell = theRow.cells[3]; //the cell that says "present"
stateCell.className = 'editing'; //so you can use CSS to remove the background colour
stateCell.replaceChild(selectBox,stateCell.firstChild); //PRESENT is replaced with the select input
selectBox.selectedIndex = 0;
}
function changeSelect(whatButton) {
isEditing = true; //don't allow it to be clicked until submission is complete
whatButton.value = 'Change';
var stateCell = selectBox.parentNode;
var theRow = stateCell.parentNode;
var editid = theRow.cells[0].firstChild.firstChild.nodeValue; //text inside the first cell
var value = selectBox.firstChild.options[selectBox.firstChild.selectedIndex].value; //the option they chose
selectBox.parentNode.replaceChild(document.createTextNode('Please wait...'),selectBox);
if( !recordvalue ) {
//allow fallback to basic HTTP
location.href = 'getupdate.php?id='+editid+'&newvalue='+value;
} else {
recordvalue.onreadystatechange = function () {
if( recordvalue.readyState != 4 ) { return; }
if( recordvalue.status >= 300 ) { alert('An error occurred when trying to update'); }
isEditing = false;
newState = recordvalue.responseText.split("|");
stateCell.className = newState[0];
stateCell.firstChild.nodeValue = newState[1] || 'Server response was not correct';
};
recordvalue.open('GET', "getupdate.php?id="+editid+"&newvalue="+value, true);
recordvalue.send(null);
}
}
</script>
If anyone has any idea why this is happening I'd be very grateful
ok managed to solve it. I moved the recordvalue.open line near the bottom inside te last else loop and it works perfectly in all browsers just don't ask me why

Categories