changing the class of an html element using javascript is unstable - javascript

I used this code to change the class of an html-element when an onclick-event occurs. The change occurs(i.e. the text color changes) but the change is not stable, it goes back to the styling of its previous class, and my javascript code doesn't seem to have any effect.
function submitrequest(){
var x = document.forms["signupform"]["name"].value;
if(x.toString().length <= 0){
var y = document.getElementById("nametd");
y.className = 'change';
}
}
What should I do to make this effect permanent?

You do not have to define a click-handler to notice that a button of a form was clicked.
A form can have an submit-button:
and when this button is clicked an submit event is fired for the form.
Furthermore when an user do not clicks on the button and just presses enter then a submit-event is fired too. So you handle both situations automatically.
I suggest that you define you function that way:
window.onload = function(){
document.getElementById('signupform').addEventListener('submit',function(e){
changeClassOfNametd();
e.preventDefault(); // this prevents the side from being reloaded by the script.
});
};
function changeClassOfNametd(){
var nameValue = document.forms["signupform"]["name"].value;
if(nameValue){ // when value is "" (zero, no signs) it is false anyway
var y = document.getElementById("nametd");
y.className = 'change';
//y.classList.toggle('change'); you can toggle classname "change" too
// which works that way class="unchange" -> class="unchange change"
// you have to define appropriate css-classes for toggle.
}
}
The Code above works whereever you put it into your html-file.

By the name of the function it is called on a form submission.
Because the form submits and it goes back to the original that was set when the new page loads.
If you want to maintain that, you would have to apply the class on the next page load. Most developers will do that with the serverside. If you do not actually want the form to submit, cancel it.

Related

Trigger validation after first submit, then after after every keystroke on input element

I am using jquery validation for everything I'm about to talk below.
so I have an input field, lets call it email. I also have a submit button for this form. Now by default the error message for email field will not kick in until I hit the submit button. Then whenever I type it will show/hide error message dependant on if it is a valid email. This check happens with every key stroke and this is a very important distinction to make so that you would understand my problem I posted below.
Now I have a background colour on the input, it is suppose to be green when validation has passed and red when it has failed. I have this part working, let me show you how I did it:
window.onload = function () {
$(".js-validate-circle").on("input", function () {
UpdateValidationCircle(this);
});
}
function UpdateValidationCircle(e) {
if ($(e).valid()) {
$(e).parent().addClass("active");
} else {
$(e).parent().removeClass("active");
}
}
The active class is what determines if its green or red. There is styling that is irrelevant I think to the question so I wont post it here.
Here is my problem: When the page loads and I start typing, it forces validation to trigger and error messages start coming in before I click the submit button for the first time. I am trying to prevent this. I want the color the start changing on typing only after the submit button was hit. Functionality of my red/green background should match jquery validation messages.
How would I accomplish something like this? I tried using on change but then the validation triggers only when the box loses focus.
jQuery(function($) { // DOM ready and $ alias in scope
// Cache elements
var $circle = $(".js-validate-circle");
var addedInputEvent = false; // Just a flag to know if we already added the evt listener
// On form submit....
$("#form").on("submit", function(event) {
// Prevent default form submit
event.preventDefault();
// Check immediately
$circle.each(UpdateValidationCircle);
// If not already assigned, assign an "input" listener
if(!addedInputEvent) {
addedInputEvent = true;
$circle.on("input", UpdateValidationCircle);
}
});
function UpdateValidationCircle() {
var $el = $(this);
$el.parent().toggleClass("active", $el.valid());
}
});
Use the keyup event instead:
$(".js-validate-circle").on("keyup", function () {
...
Assuming .js-validate-circle is your input... or if it is the form:
$(".js-validate-circle").on("keyup", "#id-of-the-input", function () {
...
If this doesn't work, we are going to need to see validate()s code and some markup.

jQuery - Bind click to specific Ajax content element

I have this form that loads using jQuery $.ajax another form inside a container.
The list:
The loaded content within the container called form_load_dropdown_content:
On the left I have two small icons for edit and add. I want to use another ajax call to run specific PHP scripts to carry on the action desired.
I have the following problem:
when I click on each icon submit and respectively reset buttons display
when I click on the reset the both submit and reset are set to display: none
when I click on any the icon again, the click remains bind to the previous icon clicked before.
This is what I am doing:
form_load_dropdown_content.on("click", ".icon", function() {
// reusable selectors
var icon_box = $(".box_edit_icons");
var button_box = $(".box_buttons");
var submit_btn = $(".box_buttons input[type='submit']");
var reset_btn = $(".box_buttons input[type='reset']");
var option_value_input = $("input.option_value");
var option_order_input = $("input.option_order");
// common functions
button_box.show();
icon_box.hide();
if($(this).hasClass("ico_edit_small"))
{
// editing
form_load_dropdown_content.on("click", "input[type='reset']", function(event){
alert("reset from edit");
button_box.hide();
icon_box.show();
});
}
else if($(this).hasClass("ico_add_small"))
{
// adding
form_load_dropdown_content.on("click", "input[type='reset']", function(event){
alert("reset from add");
button_box.hide();
icon_box.show();
});
}
How can I differentiate between the two clicks, so that when I display the submit and reset from a specific icon type to run differentiated actions?
More clear:
when I click icon_add_small and then reset => output: 'reset from add'
then when I click icon_edit_small and then reset => output: 'reset from edit'... and so on without mixing the clicks.
I truly appreciate any help. I tried everything regarding stopping the propagation of the click... but nothing worked.
-----------------------------------------------------------
Edit:
I changed the if part to the following code and it works. Should I expect any problems for unbinding the click?
if($(this).hasClass("ico_edit_small"))
{
// editing
reset_btn.off("click");
reset_btn.click(function(event){
alert("reset from edit");
button_box.hide();
icon_box.show();
});
}
else if($(this).hasClass("ico_add_small"))
{
// adding
reset_btn.off("click");
reset_btn.click(function(event){
alert("reset from add");
button_box.hide();
icon_box.show();
});
}

trouble with table of clickable buttons that needs to prevent double clicks on focused button while keeping the following ones clickable

I have a list of clickable buttons and use a flag variable to prevent a double click on the focused button. The flag works and I get the intended alert saying 'you have already clicked that'. The problem is that the following button will be treated as if it has also already been clicked and I'll get the alert again. I don't want this.
var _clickFlag = true;
/* #Volunteers is a table. Each row on the table has a button that says "accept",
I pass the function the 'event' object which I use to get specific data from that table
row and send it to a database*/
$('#Volunteers').on('click','#accept', function(event){
//if clickFlag = true then the button hasn't been clicked yet.
if(_clickFlag){
//here I send some stuff to a database. I don't want to send it twice for the same
//row, which is why I need to prevent a double click
//set clickFlag to false to prevent double submission
_clickFlag = false;
}else{
//alert if the button has been clicked once already
alert("already accepted");
}
});
Just use this:
$( "#Volunteers").unbind( "click" );
This will just make the button unclickable.
double click is a separate event, I assume you are talking about clicking the button more than once, if that is the case your variable that you defined is in the outer context is shared to all button, what you need is to define a variable inside the function and tie it to the button itself, try the below:
http://jsfiddle.net/4JFtw/
$('#Volunteers').on('click','.accept', function(event){
//if clickFlag = true then the button hasn't been clicked yet.
if(typeof this._clickFlag != 'undefined' && this._clickFlag){
//alert if the button has been clicked once already
alert("already accepted");
}else{
//here I send some stuff to a database. I don't want to send it twice for the same
//row, which is why I need to prevent a double click
alert('_clickFlag: '+this._clickFlag + ' First time processing!');
this._clickFlag = true;
}
});
In these situations I like to use attributes, ex:
$('some-button-here).attr('data-active','false') // This sets the attribute for that button
You can then check this attribute everytime one of the buttons is clicked.

Dispatching Custom Event and listening for it somewhere else (Bubbling) in IE

I can't seem to get this to work in JavaScript. I've tried using plain old JavaScript and also JQuery but nothing seems to work.
Here's my situation:
I have this PopUp "Panel" and in it I have a Button. The button has an event listener for click and I want that handler to fire off a custom event that the Panel will listen for. This is because I need to handle all the logic of the button click in the Panel.
Here's what I'm doing:
Before I launch the Panel I call a constructor for my "Class":
function PopUpStageAsssignmentTaker(content) {
PopUpStage.call(this);
this.allPagesAdded = false;
this.questionsCreated = [];// will be an array of pages that will be submitted
this.listLabel = null;
addAssignmentTakerParts.call(this);
this.popUpDiv.addEventListener("assignmentTakingSubmitEvent", handleAssignmentSubmit, true);
function handleAssignmentSubmit(event) {
alert("YESSS!");
}
}
This does quite a bit but just know that in the call to PopUpStage it creates the div that represents the Panel and saves that in this.popUpDiv. So I add a event listener to this.popUpDiv listening for some custom event that I'm making up.
Later on I have code that creates the content in the Panel and we have something like this:
SubmitQuestionTakingPage.prototype.makeContent = function(question) {
var questionWrapper = getQuestionWrapper();
var submitDiv = document.createElement("section");
submitDiv.innerHTML = "Pressing Submit will cause this Assignment to be submitted and you will be unable to make any changes after that. If this " +
"Assignment is automatically graded you will receive a Grade upon clicking submit. If this Assignment is not automatically submitted you must wait" +
" for the creator of this Assignment to assign you a Grade. To continue, please press Submit.";
submitDiv.setAttribute("class", "separatedSmaller");
questionWrapper.appendChild(submitDiv);
var submitButton = document.createElement("input");
submitButton.setAttribute("type", "submit");
submitButton.setAttribute("class", "fancyButton");
submitButton.addEventListener("click", handleSubmitButtonClick);
questionWrapper.appendChild(submitButton);
return questionWrapper;
};
function handleSubmitButtonClick(event) {
var event = document.createEvent("Event");
event.initEvent("assignmentTakingSubmitEvent", true, true);
window.dispatchEvent(event);
// $(this).trigger("assignmentTakingSubmitEvent");
}
So we create some content and in it we create a button that has a listener for click. In the click handler you can see how I fire off the event.
Problem: I'm reading that this does not work in IE under version 9+. What can I do in to make it work in all browsers? Is there a way?

Jquery: If statement help, if (radio button is checked) then Jquery, else

I have this JQuery Code, Its in the DOM Ready, on click of .deleteCatFavs it runs this function. I want to add some If functionality to this but am having trouble.
// Delete a Favorite Category,
$('.deleteCatFavs').live("click", function(){
var actionRequested = "AJAX_delFavCat";
var url = "index.php";
var catId = $("input[name=FavCats]:checked").val();
var rowId = $("input[name=FavCats]:checked").attr("id");
$.post(url, {AJAX_Action: actionRequested, rowId: rowId},
function(data){
$("#favCats").html(data);
});
});
I want this to do something like this. I have used a isset() to show what I want to do in a PHP way, I just dont know how to do this in javascript.
// On DOM Ready, Hide .deleteCatFavs
$('.deleteCatFavs').hide();
// When the input radio button is checked [name=FavCats],
if(isset($("input[name=FavCats]:checked") // <-- if radio button is selected
$(".deleteCatFavs").show(); // Then show the Delete class,
// And if the .deleteCatFavs class is clicked, then run the JQuery code above
if (.deleteCatFavs.isClicked){
Run Jquery Code here';
}
So basically, When the radio button is checked, I want to show the .deleteCatFavs class, otherwise I want it hidden on DOM ready. And also, when the .deleteCatFavs is shown and clicked, It must run the above code.
Im sure this is so simple, I just dont know how to do isset queries in Javascript.
Also, lets keep it simple.
How about:
$("input[name='FavCats']").change(function () {
/* Fired immediately after a radio button is clicked with name='FavCats' */
$(".deleteCatFavs").show();
});
Which binds an event handler to the change event--I'm assuming that if any radio button with name FavCats is clicked, you want to show .deleteCatFavs.
And:
$(".deleteCatFavs").click(function () {
/* Run jQuery code when element with class deleteCatFavs is clicked */
});
try with latest jQuery v1.6 method prop
if ( $(elem).prop("checked") )

Categories

Resources