jQuery Arguments Not Working - javascript

Having trouble with 2 things. Both of these arguments are ONLY working for the first box area generated on page load. But any subsequent ones created after aren't affected by these options. What am I doing wrong, and how can I fix it?
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
The entire code for my JS is:
$(function () {
var i = 1;
//ADD ROW
$('body').on('click', '.addPTbutton', function () {
var box = '<table class="manage-pt" id="' + i + '"><tr class="pt-entry"><td class="pt-toggle-group"><input class="pt-button togPTbutton" id="0" type="button" value="▾"><input class="pt-button addPTbutton" id="0" type="button" value="+"><input class="pt-button delPTbutton" id="' + i + '" type="button" value="-"></td><td class="pt-values"><div><input class="vendor grayout" placeholder="*Vendor Name" type="text"><select class="move-me-right-10 dropdown"><option value="0" class="placeholder" selected="selected">*Select Type</option><option value="analytics">Analytics</option><option value="chat">Chat</option><option value="remarketing">Remarketing</option><option value="other">HTML/CSS/JS</option></select><i class="icon-sort"></i><i class="icon-lock"></i></div><div><textarea class="ptCode" name="ptCode" placeholder="*Pixel Tag Code"></textarea></div><div class="page-select"><select class="dropdown"><option value="0" class="placeholder" selected="selected">*Select Page(s)</option><option value="AllPages">All Pages</option><option value="HomePage">HomePage</option><option value="VehicleDetailsPage">VehicleDetailsPage</option><option value="VehicleSearchResults">VehicleSearchResults</option><option value="ContactUsForm">ContactUsForm </option></select></div><div class="area-checkboxes"><p class="wheretosave">*Where?</p><input name="head" type="checkbox"><label for="head">Head</label><input name="body" type="checkbox"><label for="body">Body</label></div><hr/></td></tr></table>';
i++;
$("#p_scents").append(box);
return false;
});
//DELETE ROW
$('body').on('click', '.delPTbutton', function () {
var boxnum = $(".manage-pt").length;
if (boxnum <= '1') {
alert('Cannot Delete Last Remaining Row');
} else {
$(this).parents().eq(3).remove();
}
return false;
});
//TOGGLE BUTTON
$('body').on('click', '.togPTbutton', function () {
var hiddenarea = $(this).parent().next().children().next();
if ($(hiddenarea).is(':hidden')) {
//PT-VALUES OPENED
$(this).val('▾');
$(this).parent().next().children(0).children(0).attr('readonly', false);
//$(this).parent().next().children(0).children(1).prop('disabled', false);
} else {
//PT-VALUES HIDDEN
$(this).val('▸');
$(this).parent().next().children(0).children(0).attr('readonly', true);
//$(this).parent().next().children(0).children(1).prop('disabled', 'disabled');
}
//TOGGLE VISIBILITY OF HIDDEN AREA
hiddenarea.toggle();
});
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$(".dropdown").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
$(".dropdown").change();
//CHECKS FOR MORE THAN ONE 1 MANAGE-PT BEFORE ENABLES SORTABLE
$('body').on('mouseenter', '.icon-sort', function () {
if ($(".manage-pt").size() > 1) {
$('#p_scents').sortable({
disabled: false,
placeHolder: '.placeHolderHighlight',
handle: '.icon-sort',
});
} else $('#p_scents').sortable({
disabled: true,
});
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
var $onlyOne = $('.onlyOne');
$onlyOne.click(function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});
//LOCK BUTTON ON/OFF LOCKS FORM
$('body').on('click', '.icon-lock', function () {
$(this).toggleClass('locked');
var lockedarea = $(this).parents(0).eq(2);
$(lockedarea).find('input[type=text],input[type=checkbox],textarea,select').prop('disabled', function (_, val) {
return !val;
});
});
});

I assume you're using AJAX. You should be handling event delegation differently for dynamically generated DOM elements.
Ideally, you shouldn't be using body or document. Try using the nearest parent selector which is present all the time(non AJAX).
//CHECK IF TYPE/PAGE(S) IS SELECTED OR NOT
$("body").on("change", ".dropdown", function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty").children('.placeholder').remove();
});
//CHECKS TO MAKE SURE ONLY ONE CHECKBOX IS SELECTED
$("body").on("click",'.onlyOne', function () {
$onlyOne.filter(':checked').not(this).removeAttr('checked');
});

Related

How made my function affect the DOM Jquery?

Hi, I have written a webSite on Shopify and I want to disable my button and add some customs CSS class to my input if the input is not filled on my 4steps form.
I've written a piece of code with what I remember from Jquery it's been a long time since I've used this language.
This is the jQuery funct:
$(document).ready(function () {
$("#submitButton, #btn0, #btn1, #btn2").click(function () {
ValidateForm();
});
function ValidateForm() {
var invalidForm = false;
var index = 0;
var button = document.querySelector("#submitButton, #btn0, #btn1, #btn2");
$("#form__form--stepForm-" + index + "input.form__form--input").each(function () {
if ($(this).val() < 1) {
invalidForm = true;
}
});
if (invalidForm === true) {
button.disabled = true;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationInvalid");
} else if (invalidForm === false) {
button.disabled = false;
$("input.form__form--input").removeClass(".form__form--validation").addClass(".form__form--validationValid");
index++;
}
}
});
I made all my inputs like this one:
<div class="3/3 3/3--thumb 3/3--pocket grid__cell--center">
<input type="text" id="form__form--lastnameInput" name="contact[lastname]"
class="form__form--input form__form--validation" placeholder="Nom *" value required>
<div class="form__form--invalidFeedback">Veuillez saisir votre nom.</div>
</div>
And the button like this:
<button id="btn0" type="button" class="button button--primary form__form--button"
aria-label="SUIVANT" title="SUIVANT">
{% include 'icon-arrow-slider' %}
SUIVANT
</button>
As you can see it's a very basic function for the jquery and a classic HTML input but it doesn't block the button and doesn't make the CSS work either. I'd like to understand why and how to make it work for this site and the following thanks for your time and help, take care of yourself!
Your value checking is always false, consider using length function instead:
if ($(this).val().length < 1) {
invalidForm = true;
}
You may also need to prevent default behavior of your form. Instead of listening to the click, listen the submit event:
$("#form__form--contactWrapper").on('submit',function (e) {
e.preventDefault(); //the form is not sent yet
ValidateForm();
});
Then at the end of your function ValidateForm you can send it when you have all your needed validations done, like this:
$("#form__form--contactWrapper").submit();
I have get rid of all error by doing a big refacto of my code i share you my code
$(document).ready(function () {
$('[to-step]').on('click', function () {
var to_step = $(this).attr("to-step");
var current_step = $(this).closest('[stepform]').attr("stepform");
var form_error = false;
if (!($(this).hasClass("previous-btn"))) {
$('[stepform="' + current_step + '"] .form__form--input').each(function () {
if ($(this).val().length == 0) {
$(this).addClass("input--error");
form_error = true;
} else {
$(this).removeClass("input--error");
}
});
}
if (!form_error) {
if (current_step < 4 || $(this).hasClass("previous-btn")) {
$('[stepform').hide();
$('[stepform="' + to_step + '"]').fadeIn();
}
}
});
$("#submitButton").on("click", function (event) {
event.preventDefault();
if ($("#form__form--radioRgpd:checked").length == 1) {
$("#contact_form").submit();
} else {
$(".form__form--radioRgpdLabel").addClass("label--error");
}
});
});
this piece of code gonna check at what step i am in my 4 'pages' form and add the proper css class if the form is bad filled or not filled.

Jquery, select dropdown option on Event

I have a Jquery with event keyup.
It select dropdownList(CityId) option, which text is liked/samme as a user write in inputbox(finpost).
The problem is that only work once.. I cant see whats wrong ?!
Help
$(document).ready(function () {
$('#finpost').keyup(function ()
{
$("#CityId > option").each(function ()
{
var t = this.text.toUpperCase();
if (t.indexOf($('#finpost').val().toUpperCase()) != -1)
{
$(this).attr("selected", 'true');
return false;
}
});
});
});
This work only once because your list can have only one selected option per time, but in your script logic you are setting attribute selected to true every time you find a matching without re-initializing others options
I think you should be good to go if you try this
$(document).ready(function () {
$('#finpost').keyup(function ()
{
var matchingFound = false;
$("#CityId > option").each(function ()
{
var t = this.text.toUpperCase();
if (t.indexOf($('#finpost').val().toUpperCase()) != -1 && !matchingFound)
{
$(this).attr("selected", 'true');
matchingFound = true;
}
else {
$(this).attr("selected", "false");
}
});
});
});
Now its working. The problem wass this linie:
$(this).attr('selected', true);..
I changed it to $(this).prop('selected', true);
and its work
$(document).ready(function () {
$('#finpost').keyup(function () {
$("#CityId > option").each(function () {
var t = this.text.toUpperCase();
if (t.indexOf($('#finpost').val().toUpperCase()) != -1) {
$(this).prop('selected', true);
return false;
}
});
});
});

show div on wrong field input

I am using the following script to show a div when the correct input is filled in.
But I would like to show another div as long as the input is filled in wrong..
$(document).ready(function () {
$('#inputId').bind('keyup', function () {
$('#volgende div').hide();
var divName = this.value;
if (divName) {
$('#volgende #' + divName).show();
}
});
});
JSfiddle:
http://jsfiddle.net/QwCQm/
I should add an 'else' somewhere but I can't seem to make it work..
Try with:
$(document).ready(function () {
$('#inputId').bind('keyup', function () {
$('#volgende div').hide();
var divName = $(this).val(),
div = $('#volgende #' + divName);
if (div.length) {
div.show();
} else {
// do something else
}
});
});
Here's a simple and crude example:
Demo
HTML
<input type="text" id="inputId" maxlength="8" autocomplete="off">
<div id="volgende">
<div id="abc-good" class="btn">Nice job! You know your ABC's</div>
<div id="abc-bad" class="btn">Not there yet...</div>
</div>
JS
$('#inputId').bind('keyup', function () {
$('#volgende div').hide();
var desiredVal = 'abc'; // what the user SHOULD type
var divName = this.value; // what the user DID type
var msgKey = divName == desiredVal ? 'good' : 'bad';
// if the user has typed something, show the message
if( divName.length > 0 )
$('#'+desiredVal+'-'+msgKey).show()
});
You should try a change event. So...
$('#inputId').bind('change', function () {
if ($(this).val() != "[CORRECT_INPUT]") {
$('#my_incorrect_input_div').show();
}
});

Disable submit if checkbox value has not changed from initial page-render

I have a script that does not allow submit until the form value is changed from the initial page-render.
Everything works, except for the radio buttons. When I try to check or uncheck them, they have no effect on the button.
Anyone see what is wrong? (I want to do a check to see if one or more of the checkboxes has changed from the initial page-render)
$(document).ready(function () {
var button = $('#submit-data');
$('input, select, checkbox').each(function () {
$(this).data('val', $(this).val());
});
$('input, select, checkbox').bind('keyup change blur', function () {
var changed = false;
$('input, select, checkbox').each(function () {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
});
$('#submit-data').prop('disabled', !changed);
});
});
Edit:
Checkbox html:
<input checked="checked" id="contactemail" name="contactemail" type="checkbox" />
<input id="contactsms" name="contactsms" type="checkbox" />
<input checked="checked" id="contactphone" name="contactphone" type="checkbox" />
Edit 2:
New code from answer from Marikkani Chelladurai. It is almost working, but it only works if the checkbox is not checked initially, and then checked by the user. Link to JSFiddle
$(document).ready(function() {
var button = $('#submit-data');
$('input, select').each(function () {
$(this).data('val', $(this).val());
});
$('input[type=radio], input[type=checkbox]').each(function (e) {
$(this).data('val', $(this).attr('checked'));
}); //For radio buttons
$('input, select').bind('keyup change blur', function (e) {
var changed = false;
if (e.target.type == "radio" || e.target.type == "checkbox" ) {
if($(this).data('val') != $(this).attr('checked')){
changed = true;
}
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}
$('#submit-data').prop('disabled', !changed);
});
});
Link to JSFiddle
You can handle radio buttons and checkboxes by a different way as follows
$('input, select').not('[type=checkbox]').each(function () {
$(this).data('val', $(this).val());
});
$('input[type=radio], input[type=checkbox]').each(function (e) {
$(this).data('val', $(this).is(':checked'));
}); //For radio buttons
$('input, select').bind('keyup change', function (e) {
var changed = false;
if (e.target.type == "radio" || e.target.type == "checkbox" ) {
console.log($(this).is(':checked'));
console.log($(this).data('val'));
if($(this).data('val') != $(this).is(':checked')){
changed = true;
}
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}
As the comments say, radio buttons use the checked property. Pass in event to your each and check the target.type:
$('input, select, checkbox').each(function (e) {
if (e.target.type == "radio") {
//check radio
} else {
if ($(this).val() != $(this).data('val')) {
changed = true;
}
}
});

How to edit and update <td> value when double click Jquery

I have written my code such that when user double clicks on a <td> element I am:
appending am <input> of type="text"
adding a value to it and update it if the user clicks on enter
Here is the my problem:
If user double clicks on <td> and clicks on another <td> without pressing enter, I need the initial <td>'s <input> to be reset to previous value.
// Selecting the table <th> odd elements
$("#div table td").dblclick(function(){
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
function updateVal(currentEle, value)
{
$(currentEle).html('<input class="thVal" type="text" value="'+value+'" />');
$(".thVal").focus();
$(".thVal").keyup(function(event){
if(event.keyCode == 13){
$(currentEle).html($(".thVal").val().trim());
}
});
$('body').not(".thVal").click(function(){
if(('.thVal').length != 0)
{
$(currentEle).html($(".thVal").val().trim());
}
});
}
Please help me.
I don't want to use jeditable datatable.
Here in your case you need .stopPropagation(): http://jsfiddle.net/jFycy/
$(function () {
$("#div table td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
});
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val().trim());
}
});
$(document).click(function () { // you can use $('html')
$(currentEle).html($(".thVal").val().trim());
});
}
Instead doing click on body do the event on document or html which is the parent elem of all others elems.
Fixed the last answer. by checking who triggered the event i can prevent the double click issue on the input.
Also, with the .off('click') you dont have the problem where every td you updated before changes with the last one.
$(function () {
$(".inner").dblclick(function (e) {
if($(event.target).attr('class')!="thVal")
{
e.stopPropagation();
var currentEle = $(this);
var value = $(this).html();
updateVal(currentEle, value);
}
});
});
function updateVal(currentEle, value) {
$(document).off('click');
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
$(".thVal").focus();
$(".thVal").keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html($(".thVal").val());
}
});
$(document).click(function () {
if($(event.target).attr('class')!="thVal")
{
$(currentEle).html($(".thVal").val());
$(document).off('click');
}
});
}
I know its an old topic... but the answer that posted here didnt worked well because of the click event on the input, I took the answer and modified it
$(".daily-signals > tbody > tr > td").dblclick(function (e) {
e.stopPropagation(); //<-------stop the bubbling of the event here
var currentEle = $(this);
var value = $(this).html();
console.log('fire!');
updateVal(currentEle, value);
});
function updateVal(currentEle, value) {
$(currentEle).html('<input class="thVal" type="text" value="' + value + '" />');
var thVal = $(".thVal");
thVal.focus();
thVal.keyup(function (event) {
if (event.keyCode == 13) {
$(currentEle).html(thVal.val());
save(thVal.val());
}
});
thVal.focusout(function () {
$(currentEle).html(thVal.val().trim());
return save(thVal.val()); // <---- Added missing semi-colon
});
}
function save(value) {
console.log(value);
}
the save function will make the ajax request

Categories