I'm trying to do a very simple task but for some reason I can't do it.
basically I am using the if statement to change the value of an input field using javascript but it doesn't work!
this is my code:
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
and the HTML looks like this:
<input type="text" id="colour" name="colour" class="colour" value="171515"/>
so what i need to do is this:
I launch a page and the input field is on my page with the value of value="171515", and then I press a button and that should change the value of the input field to value="db0000", and then I press the button again, and it should change the value of the input button to value="171515" and I need to do the same steps as many times as I want.
currently, it seems like it gets into a loop action and thats why it doesn't change the value of input field! (correct me if i'm wrong).
any help would be appreciated.
Thanks
EDIT:
The javascript code above is executed like so:
$(params.addPplTrigger).bind('click', function(e){
e.preventDefault();
///////// THE CODE ABOBE WILL GO HERE///////////
}
You're just missing an else:
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
else if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
What happens in your original code
Case 171515:
first if condition evaluates to true, because the value is 171515
value gets changed to db0000
second if condition evalutes to true again, because the value is db0000 now
value gets changed back to 171515
Case db0000:
first if condition gets evaluates to false, because the value is not 171515
the value remains the same
second if condition gets evaluates to true, because the value is db0000
value gets changed to 171515
So, in both cases you'd end up with 171515.
since you are doing :
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}
and then reverse
if (document.getElementById("colour").value == "db0000"){
document.getElementById("colour").value = "171515";
}
so you are not able to see the change .use else instead of second if.
if (document.getElementById("colour").value == "171515"){
document.getElementById("colour").value = "db0000";
}else{
document.getElementById("colour").value = "171515";
}
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 have a form with several text fields and I would like the add button to be enabled when the required fields are filled in. The button is disabled by default in the HTML. In Firebug it appears the blur function fires but the that the if statement isn't reached.
$(".cd-form :input").blur(function(){
var ok=true;
$("#signup-firstnmame,#signup-surname","#signup-Address1","#signup-City","#signup-Postcode","#signup-Email","#signup-Mobile").each(function(){
/* if ($(this).val()==="")*/
if ($('#signup-firstnmame').val() !== "" && $('#signup-surname').val() !== "" && $('#signup-Address1').val() !== "" && $('#signup-City').val() !== "" && $('#signup-Postcode').val() !== "" && $('#signup-Email').val() !== "" && $('#signup-Mobile').val() !== "")
$("#AddData").prop("disabled",false);
else
$("#AddData").prop("disabled",true);
});
});
The commas are supposed to be a part of the selector, not separate parameters.
$('#signup-firstname, #signup-surname, #signup-Address1, ...
Also, if you're checking all of the fields, as in your if statement, you don't need to do that once for each field, it'll suffice to do it once.
If you would consider adding a class to the relevant fields, your function would be much more readable, i.e:
$('#AddData').prop('disabled', $('.required-field[val=""]').length > 0);
To Start, I think it would be smart to add a unique class to the inputs that you care about. this way you can do something along the lines of:
$('.yourClass').on('input', function() {
var x = true;
$('.yourClass').each(function() {
this = $(this); //cast it to jQuery obj (ez ref)
if (this.val() == "")
x = false;
} );
} );
Basically, every time someone enters something into the fields, jQuery will iterate through your inputs checking the values and adding 1 to x. If x is equal to the number of elements you are checking then it will enable the button.
This is not the most elegant solution but how I got around the same issue you were having when I was rushed into finishing a project.
Modified my answer with what #JaredT mentioned about the boolean, far more elegant. I am sure this could be improved further though, hope this gets the ball rolling.
as you can see here jsfiddle.net/TTU4Z/1/
The jquery code in question is below and if i run it without all my code (like in jsfiddle) it run perfectly. but with all my code doesn't run.
$(document).ready(function() {
// This button will increment the value
$('.plus').click(function(e){
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If is not undefined
if (!isNaN(currentVal)) {
// Increment
$('input[id='+fieldName+']').val(currentVal + 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
// This button will decrement the value till 1
$(".minus").click(function(e) {
// Stop acting like a button
e.preventDefault();
// Get the field name
fieldName = $(this).attr('field');
// Get its current value
var currentVal = parseInt($('input[id='+fieldName+']').val());
// If it isn't undefined or its greater than 0
if (!isNaN(currentVal) && currentVal > 0) {
// Decrement one
$('input[id='+fieldName+']').val(currentVal - 1);
} else {
// Otherwise put a 0 there
$('input[id='+fieldName+']').val(0);
}
});
});
Clicking on "add" button all is good, but when you click in one of minus or plus button it delete all.
It should increase or decrease the val of the relative input as you can see, but nothing change if i try to edit everything in those functions.
What to do?
Since you are appending elements dynamically you have to use event delegation in this situation. Actually the registered events are not invoking in your context, that's why the buttons are exhibiting their original behavior.
Try,
$(document).on('click','.plus',function(e){
and
$(document).on('click','.minus',function(e){
Additionally, the selector that you are framing dynamically contains some meta-characters, just pass that as a string or you have to escape it, in order to make your code work properly.
DEMO
New Demo after fixing your concatenation issues. And in that demo, i just removed the attribute selectors like [id='blah'] and replaced that with $('#blah').
DEMO - I
See updated fiddle http://jsfiddle.net/LfNmh/
You had your x variable inside the code string where it should have been in the code. line 15 ..
var numPortata = '<td><button class="minus" field="portata'+x+'">-</button><input id="portata'+x+'" type="number" name="numPortata[]" value="1" size="10" min="1" max="10" step="1" required><button class="plus" field="portata'+x+'">+</button></td>';
I also changed the code so that the events are attached at the document level as Rajaprabhu said.
I swear I'm going to learn more JavaScript...
I have this page (which really an include file in another ASP page, but I copied the correct HTML and made it so it'd load by itself for my testing purposes):
FO Samples
This is how it should show when they first load it. If they choose one of the other radio buttons, it should HIDE the 2 dropdown boxes. Using this code (something I found from someone else's question on here), its working.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
But I can't figure out how to make it show them again if they go back to the "I wanna pick my own!" radio. The value of SAMPGROUP is the ID from the database of that sample category group. So it won't necessarily be in numerical order, it might skip #'s (if we delete a category or something). Basically, it should show the dropdowns if SAMPGROUP = 0 and not if its anything else!
I tried changing my code to this (95 being the value of SAMPGROUP for the "Autumm" option), but it doesn't seem to have made a difference.
<script type="text/javascript">
function ChangeDropdowns(value) {
if (value == "0") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'block';
} else if (value == "95") {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
else {
document.getElementById('SAMPLEDROPDOWN').style.display = 'none';
}
}
</script>
Any help would be greatly appreciated!!
Mahalo!
You are not setting the "value" in your onchange event, thus it's never equal to 0. Try changing this:
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns()" checked />
to
<input type="radio" name="SAMPGROUP" value="0" OnChange="Javascript:ChangeDropdowns(0)" checked />
Here is the fiddle.
Good luck.
You may not be passing any value to the parameter "value" on calling the function ChangeDropdowns. Please ensure you pass the value like ChangeDropdowns(0) etc..
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);