I have a function where if the user clicks on a button, it will display a value in the textbox and it will perform a trigger to another function after a '#btn' button is clicked:
function addwindow(numberAnswer, gridValues, btn) {
$('#mainNumberAnswerTxt').val(numberAnswer).data('data-ignore',true);
$('#btn'+gridValues).trigger('click');
}
Now what I want to do is that:
if the user clicked on the "Add" button, then display the number from the "Number of Answers" column into the textbox or in other words perform this from the addwindow() function:
$('#mainNumberAnswerTxt').val(numberAnswer).data('data-ignore',true);
If the user has clicked on a #btn+gridValues button, then display the number in the textbox of the number of buttons which are currently turned on or in other words perform this code:
if ($('#mainNumberAnswerTxt').data('data-ignore') != true) {
$('.answertxt', context).val(context.find('.answerBtnsOn').length > 0 ? context.find('.answerBtnsOn').length : 0);
}
The problem is that step 1 works fine, it does display the number from the "Number of Answers" column in the textbox after the user has clicked on the "Add" button.
The problem is step 2, it is not displaying the correct number on how many buttons are currently turned on after the user has clicked on the #btn+gridValues button.It just doesn't change the number in the textbox.
Does anyone know why this is happening and how thi can be fixed?
DEMO:
Here is a demo of the application. Please follow the steps below:
Step 1: On left hand side you will see a green plus button, click on it and it opens up a modal window.
Step 2: In modal window there is a search bar, type in "AAA" and submit search, you will see a bunch of rows appear.
Step 3: In the last row, you see under "Number of Answer" colum that it contains the number 4, click on the "Add" button within this row, the modal window will close.
You will see that the textbox displays the number 4 in the textbox which is fine as that was the number within the row under the "Number of Answers" column when you added the row.
But below is the problem:
Step 4: If you click on the "Open Grid" link and select button 3, you will see the letter buttons below change to A-C with only letter "B" turned on.
In the textbox it should display number 1 as only 1 button is turned on, but it doesn't display this number and that is the problem I am having.
How can this problem be fixed?
The problem comes from the fact taht you're setting the data-attribute to false on the $('#mainNumberAnswerTxt') but you're checking against the inputs (this in the click).
One solution would be to do the following test if ($('#mainNumberAnswerTxt').attr('data-ignore') != true)
EDIT
To ensure that the ignore process execute only once (when the grid is reloaded after the modal), you'll have to change what's inside the block after the test:
if ($('#mainNumberAnswerTxt').data('ignore') != true) {
$('.answertxt', context).val(context.find('.answerBtnsOn').length > 0 ? context.find('.answerBtnsOn').length : 0);
} else {
/*reset the ignore flag*/
$('#mainNumberAnswerTxt').data('ignore',false);
}
EDIT2
The main problem is that your reaffecting the $('#mainNumberAnswerTxt').val(numberAnswer) after setting it. Your trying to ignore it through the ignoreattribute.
What i would adivse, would be to remove every occurence to that attribute and to change the following function
function addwindow(questionText,textWeight,numberAnswer,gridValues,reply,btn) {
var answers = $.map(btn.split(''),function(chr){ return "#answer"+chr; }).join(', ');
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
var myNumbers = {};
myNumbers["A-C"] = "3";
myNumbers["A-D"] = "4";
myNumbers["A-E"] = "5";
myNumbers["A-F"] = "6";
myNumbers["A-G"] = "7";
gridValues = myNumbers[gridValues];
$('#mainNumberAnswerTxt').show();
$('#mainNumberAnswerTxt').val(numberAnswer).data('ignore',true);
$('#mainGridTxt').val(gridValues).parent().append($('.optionTypeTbl'));
$('#btn'+gridValues).trigger('click');
$('.answers.answerBtnsOn').removeClass('answerBtnsOn').addClass('answerBtnsOff');
$(answers).addClass("answerBtnsOn").siblings().addClass('answerBtnsOff');
}
$.modal.close();
return false;
}
to :
function addwindow(questionText,textWeight,numberAnswer,gridValues,reply,btn) {
var answers = $.map(btn.split(''),function(chr){ return "#answer"+chr; }).join(', ');
if($(plusbutton_clicked).attr('id')=='mainPlusbutton') {
var myNumbers = {};
myNumbers["A-C"] = "3";
myNumbers["A-D"] = "4";
myNumbers["A-E"] = "5";
myNumbers["A-F"] = "6";
myNumbers["A-G"] = "7";
gridValues = myNumbers[gridValues];
$('#mainNumberAnswerTxt').show();
$('#mainGridTxt').val(gridValues).parent().append($('.optionTypeTbl'));
$('#btn'+gridValues).trigger('click');
/* moved the following line below the click simulation,
hence its value will be changed regardless of what happened during the click simulation*/
$('#mainNumberAnswerTxt').val(numberAnswer);
$('.answers.answerBtnsOn').removeClass('answerBtnsOn').addClass('answerBtnsOff');
$(answers).addClass("answerBtnsOn").siblings().addClass('answerBtnsOff');
}
$.modal.close();
return false;
}
In order to modify the value after the visual changes took place.
Use data instead of attr - attr takes a string, data takes JavaScript objects.
Related
I have a form with numeric fields, text fields and drop down lists. I have implemented functionality were if a field is changed from original value then button is enabled for submit. If field is changed back to it original value button should(is) disabled.
PROBLEM: Current issue at the moment is
- if I change two different fields, then button is enabled as expected. But then if I revert only one of these edited fields back to its original value, submit button is disabled. Expected behavior is "as long as there's a changed field that is valid, then button should remain enabled for submit".
Conditions for button state
for all fields - if original value is changed and is not empty - enable button
for numeric fields - if entered/changed value is a valid number - enable button
*so if any of these conditions are not met, then button should stay disabled
Current Code
Current implementation and why it was implemented this way
$("input[name='q_description'],[name='q_sellprice'],[name='profit'],[name='grossProfit'],[name='markUp']").change(function () {
var originalValue = ($(this)[0].defaultValue);
var currentValue = $(this).val();
var changed = false;
var button = $('#submit-data');
//numeric fields
var sellprice = parseFloat($('#q_sellprice').val());
var profit = parseFloat($('#profit').val()); var grossProfit = parseFloat($('#grossProfit').val());
var markUp = parseFloat($('#markUp').val());
//text fields
var description = document.getElementById("q_description").value;
//alert("Numeric values:" + getFieldValues );
//$('input, select').bind('keyup change blur', function () {
if (description == "" || isNaN(sellprice) || isNaN(profit) || isNaN(grossProfit) || isNaN(markUp))
{
/*change background color to red for invalid or empty field*/
$(this).css("background", "#fd6363");
document.getElementById("submit-data").disabled = true;
}
else if ((originalValue != currentValue) ) {
/*change background color to yellow if value changed*/
$(this).css("background", "#FFE075");
document.getElementById("submit-data").disabled = false;
}
else if (originalValue == currentValue) {
/*original and current values match, reset background of that field to white*/
$(this).css("background", "#FFFFFF")
document.getElementById("submit-data").disabled = true;
}
else {
//to do
}
//});
});
On the first line, I dont have it this way
$("input[type=text]").change(function () {
because there is some fields on the form/page that I wanted to ignore for affecting the state of the submit button. That is why I have specified those particular fields on the .change
Also to check isNaN for the numeric fields. I probably can identify id the required fields by class names and add them to an array and just check that instead of the numerous declarations
var numericFields = document.getElementsByClassName("numeric_fields");
var getFieldValues = new Array();
for (i in numericFields) {
var singleValue = numericFields[i].value;
if (singleValue !== "" && singleValue !== undefined ) {
getFieldValues.push(singleValue);
}
}
but I had an issue, where the invalid check if statement part of the code wasn't getting hit with that implementation.
Anyways the main issue that I would like to solve at the moment, is to stop the button getting disabled when I revert one field back to its original value when multiple fields have been changed/edited to (from original) other valid states.
UPDATE
Further checks to clarify issue. I added an alert message message to see/check which if/else statement is getting hit each time any field is changed
if (description == "" || isNaN(sellprice) || isNaN(profit) || isNaN(grossProfit) || isNaN(markUp))
{
/*change background color to red for invalid or empty field*/
alert("1") //disable button
}
else if ((originalValue != currentValue) ) {
/*change background color to yellow if value changed*/
alert("2") //enable button
}
else (originalValue == currentValue) {
/*original and current values match, reset background of that field to white*/
alert("3") //default -> disable button
}
Now if a previously edited field is reverted back to its original value, while another has been changed, its hitting the last else statement alert("3), meaning the check is done per individual field that is currently being edited and not all the specified fields that I have specified from the form.
I am trying to get two buttons groups with checkboxes mutually exclusive.
Here's my current result on this JS Fiddle
As you can see, there are four divs (with id="UserVsComputer", id="User1VsUser2", id="PlayableHits" and id="button-new-game").
I want the two first <div> ( UserVsComputer and User1VsUser2 ) to be mutually exclusive when we click on the checkbox of concerning <input> (i.e corresponding to the right <div>).
In JavaScript part, I did:
// Select the clicked checkbox for game type
$('input.game').on('click',function(){
setGameType();
});
function setGameType() {
// Get state of the first clicked element
var element = $('#UserVsComputer input.game');
var checkBoxState = element.prop('checked');
// Set !checkBoxState for the sibling checkbox, i.e the other
element.siblings().find('input.game').prop('checked',!checkBoxState);
updateGameType();
}
function updateGameType() {
// Set type of game
if ($('#UserVsComputer input').prop('checked'))
gameType = 'UserVsComputer';
else
gameType = 'User1VsUser2';
}
I don't want the <div id="PlayableHits" class="checkbox"> to be concerned by this mutual exclusion on two first checkboxes.
For example, below a capture showing that I can set the two first checkbox to true without making them exclusive:
What might be wrong here?
Try the following - it uses the target of the click event to ascertain which checkbox was checked:
// Select the clicked checkbox for game type
$('input.game').on('click',function(e){
setGameType(e.target);
});
function setGameType(cb) {
var container = $(cb).parent().parent();
var checkBox = $(cb);
var checkBoxState = checkBox.prop('checked');
// Set !checkBoxState for the sibling checkbox, i.e the other
container.siblings().find('input.game').prop('checked', !checkBoxState);
updateGameType();
}
function updateGameType() {
// Set type of game
if ($('#UserVsComputer input').prop('checked')) {
gameType = 'UserVsComputer';
} else {
gameType = 'User1VsUser2';
}
}
There are other bits which could use some attention (the hardcoded .parent().parent() isn't pretty but works in this case..
I am making a new website. As is what I'm doing is a gallery of videos by clicking shows me a video in modal, in total only shows me 1 large video with text and small 3 videos below where you can display more items. I need you to click show me more out a new row with 3 computer elements by al-md-4 columns. This step I have done but I have 2 problems:
Default with Javascript shows me 2 rows instead of just one, will define in the JS 1 and showing me appear 2
I also wish there was another button to "hide" and was hiding whenever I click a row.
Then I attached the complete code to where I could do.
http://www.bootply.com/vLeA1VQoYF
Need help!!
Thank you so much! Greetings from Spain
Here is my fiddle
And JS:
$('.mydata:gt(0)').hide().last().after(
$('<a />').attr('href','#').attr('id','btn_less').text('Show less').click(function(){
var a = this;
$('.mydata:visible:gt(0)').last().fadeOut(function(){
if ($('.mydata:visible:gt(0)').length == 0) {
$(a).hide();
} else if($("#btn_more:not(:visible)")){
$("#btn_more").show();
}
});
return false;
})
).after($('<span />').text(' ')
).after(
$('<a />').attr('href','#').attr('id','btn_more').text('Show more').click(function(){
var a = this;
$('.mydata:not(:visible):lt(1)').fadeIn(function(){
if ($('.mydata:not(:visible)').length == 0) {
$(a).hide();
} else if($("#btn_less:not(:visible)")){
$("#btn_less").show();
}
}); return false;
}));
Tell me if I misunderstood you and you need something else.
I have a webpage I'm building where I need to be able to select 1-9 members via a dropdown, which then provides that many input fields to enter their name. Each name field has a "suggestion" div below it where an ajax-fed member list is populated. Each item in that list has an "onclick='setMember(a, b, c)'" field associated with it. Once the input field loses focus we then validate (using ajax) that the input username returns exactly 1 database entry and set the field to that entry's text and an associated hidden memberId field to that one entry's id.
The problem is: when I click on the member name in the suggestion box the lose focus triggers and it attempts to validate a name which has multiple matches, thereby clearing it out. I do want it to clear on invalid, but I don't want it to clear before the onclick of the suggestion box name.
Example:
In the example above Paul Smith would populate fine if there was only one name in the suggestion list when it lost focus, but if I tried clicking on Raphael's name in the suggestion area (that is: clicking the grey div) it would wipe out the input field first.
Here is the javascript, trimmed for brevity:
function memberList() {
var count = document.getElementById('numMembers').value;
var current = document.getElementById('listMembers').childNodes.length;
if(count >= current) {
for(var i=current; i<=count; i++) {
var memberForm = document.createElement('div');
memberForm.setAttribute('id', 'member'+i);
var memberInput = document.createElement('input');
memberInput.setAttribute('name', 'memberName'+i);
memberInput.setAttribute('id', 'memberName'+i);
memberInput.setAttribute('type', 'text');
memberInput.setAttribute('class', 'ajax-member-load');
memberInput.setAttribute('value', '');
memberForm.appendChild(memberInput);
// two other fields (the ones next to the member name) removed for brevity
document.getElementById('listMembers').appendChild(memberForm);
}
}
else if(count < current) {
for(var i=(current-1); i>count; i--) {
document.getElementById('listMembers').removeChild(document.getElementById('listMembers').lastChild);
}
}
jQuery('.ajax-member-load').each(function() {
var num = this.id.replace( /^\D+/g, '');
// Update suggestion list on key release
jQuery(this).keyup(function(event) {
update(num);
});
// Check for only one suggestion and either populate it or clear it
jQuery(this).focusout(function(event) {
var number = this.id.replace( /^\D+/g, '');
memberCheck(number);
jQuery('#member'+number+'suggestions').html("");
});
});
}
// Looks up suggestions according to the partially input member name
function update(memberNumber) {
// AJAX code here, removed for brevity
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
document.getElementById('member'+memberNumber+'suggestions').innerHTML = self.xmlHttpReq.responseText;
}
}
}
// Looks up the member by name, via ajax
// if exactly 1 match, it fills in the name and id
// otherwise the name comes back blank and the id is 0
function memberCheck(number) {
// AJAX code here, removed for brevity
if (self.xmlHttpReq.readyState == 4) {
var jsonResponse = JSON.parse(self.xmlHttpReq.responseText);
jQuery("#member"+number+"id").val(jsonResponse.id);
jQuery('#memberName'+number).val(jsonResponse.name);
}
}
}
function setMember(memberId, name, listNumber) {
jQuery("#memberName"+listNumber).val(name);
jQuery("#member"+listNumber+"id").val(memberId);
jQuery("#member"+listNumber+"suggestions").html("");
}
// Generate members form
memberList();
The suggestion divs (which are now being deleted before their onclicks and trigger) simply look like this:
<div onclick='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
<div onclick='setMember(450, "Chris Raptson", 2)'>Chris Raptson</div>
Does anyone have any clue how I can solve this priority problem? I'm sure I can't be the first one with this issue, but I can't figure out what to search for to find similar questions.
Thank you!
If you use mousedown instead of click on the suggestions binding, it will occur before the blur of the input. JSFiddle.
<input type="text" />
Click
$('input').on('blur', function(e) {
console.log(e);
});
$('a').on('mousedown', function(e) {
console.log(e);
});
Or more specifically to your case:
<div onmousedown='setMember(123, "Raphael Jordan", 2)'>Raphael Jordan</div>
using onmousedown instead of onclick will call focusout event but in onmousedown event handler you can use event.preventDefault() to avoid loosing focus. This will be useful for password fields where you dont want to loose focus on input field on click of Eye icon to show/hide password
I have a jsfiddle here
Please follow steps below in order to use the little application in the fiddle:
Click on "Open Grid" link and select a numbered button. A bunch of letter buttons will appear underneath. If you start selecting answer buttons then they turn green and in the "Number of answers" textbox above will start counting how many buttons you have turned on.
If you deselect all answer buttons however so that no answer buttons are turned on, then the text box above does not display 0 but instead display 1.
This is because of the code below:
var container = $btn.closest(".optionAndAnswer");
// here the zero gets assigned
var answertxt = $(".answertxt", container);
var numberison = $(".answerBtnsOn", container).length;
if (answertxt.val() == 1 && numberison == 0) {
numberison = 1;
}
answertxt.val(numberison);
I have include a comment in the jsfiddle in block capitals to state where this block of code is in the fiddle.
What I want to do is that if the option selected from the grid is either "True or False" or "Yes or No", then perform the code above where if no answer button is highlighted then the textbox value is 1. If it is any other option then if no answer buttons are selected then the textbox value should be 0.
How can this be achieved?
Fixed it, as you can see below, I'm checking if the selected type of input is true/false yes/no and by that I determine which code to run:
// ...
var maxRowValue = $('.gridTxt', container).val();
if (maxRowValue === 'True or False' || maxRowValue === 'Yes or No') {
if (answertxt.val() == 1 && numberison == 0) {
numberison = 1;
}
}
answertxt.val(numberison);