If the input field is blank, set a specific value - javascript

I'm designing a shopping cart system for my site. I have an input to enter the quantity for each item, with the value 1 automatically put in. The problem is, if someone clicks in the input and deletes the 1, leaving the field blank, then the item isn't added to the cart.
How can I set a 1 in the input field if it is blank, either using js or jquery? Or if the field is blank have the form automatically submit a 1?

Something like this should work:
$("#input_ID").blur(function() {
if($.trim($(this).val()) === "") {
$(this).val("1");
}
});
If it needs to be a group of inputs, simply give them a common class and change:
$("#input_ID").blur( . . .
. . . to:
$(".class_name").blur( . . .

var value = $(your_input).val();
if ( value == '' ) value = 1

The following solution is only js no jquery.
Within your internal function, wherever you are saving the input.
For example:
let itemQuantity = document.getElementById("item_quantity");
//you can also add account for space or other non numeric values (consider looking into regex)
if (itemQuantity === ""){
itemQuantity = 1
// or "1" depending on how you need to pass the values
return taskPriority;
}
alternate:
if (itemQuantity.value === ""){
itemQuantity = 1
// or "1" depending on how you need to pass the values
}
The first one will force the user to reset default to 1 and then add to cart again.
Second will by default set it to 1 if they input blank values.
that should allow you to set a default value.

Related

I am facing problems in Conditional Statements With input Fields Of bootstrap

Here Is My Logic:
It Didn't Work :(
function ShowDropMenu(){
var numfiled = document.getElementById('numpeple'); //I Want Whenever Someone Enters a Number In Input Field It Should Display The Dropdown Menu?
if (numfiled < 0 ) {
document.getElementById('dropmock').style.display="block"
}
else{
alert('Please Add Atleast 1 Or More People to go ahead)
}
}
I Don't Know What's Went Wrong?
numfiled is an Element, so comparing it with a number won't do anything meaningful.
You want the value of the Element. Additionally, since the value is always a string, you want to parse it as a number. For example:
var numfiled = parseInt(document.getElementById('numpeple').value);
Note: This assumes #numpeple refers to an <input> element, inferred from the comment in the code: "Someone Enters a Number In Input Field"

Input text validation jquery

I'm using Jquery Framework, I'm trying to validate input data, which is not equal to null or empty string. My approach is to validate data in a single line as I'm maintaining cookies storage. My question is, how can I validate input text that value its not an empty string, similarly I checked radio buttons and check boxes that are checked. How can I validate input[type='text'] with same condition input[value !=''] in a single line.
Here's my code:
_strFormElements = "input[type='text']," +
"input[type='checkbox']:checked," +
"input[type='radio']:checked," +
"input[type='image']," +
"input[type='file']," +
"select," +
"textarea";
I then checking as follow, but I want to check and validate before theses checks as my init method creates empty feilds before this.
if (elem.is('input:text') || elem.is('input:hidden') || elem.is('input:image') ||
elem.is('input:file') || elem.is('textarea')) {
elem.val(value);
}
My Try:
I've tried input[type='text' value != ''] but I'm unable to check this in a single line.

How to validate forms (which are generated dynamically)?

Can you please tell me how to do validation in a form which is generated dynamically? I am using one plugin dform.js which converts JSON to form. I am to do that validate of fields.
http://jsfiddle.net/Xe3FG/2/
I take help from this.
https://github.com/daffl/jquery.dform
In my demo, I take 2 number fields. If the user enters a string and go to next field, I need it to display an error in front of the field, "please enter only numbers." I need the same with second field.
Can we do only using drom.js or validation.js?
I am able to validate when user enters data in the field and then press enter.
So I used blur event. It is not a good practice to use blur event on every field. Can you give a different way and a good way to validate?
("#totalRetryCount").blur(function() {
// Number element type returns empty value when NaN
if ( $('#totalRetryCount').val() == '' )
alert('enter a number');
});
$("#totalRepeatCount").blur(function(event) {
// Number element type returns empty value when NaN
if ( $('#totalRepeatCount').val() == '' )
alert('enter a number');
I used these two blur events. I don't want to use these events. Can we do these validations another way?
I've already explained to you how to do this in your last question and provided you with a fully working example which you've seemed to completely ignore. In this case, you would just need to check if the value is an empty string, as that is the default value of a number type input field containing non-numeric data.
Fiddle demo
$("#testSuiteConfigurationform").validate(validateInputParameters());
function validateInputParameters() {
jQuery.validator.addMethod("onlyNumbers", function(value, element) {
return value != "";
}, " Please enter only numbers");
var validation = {
onfocusout : function(element) {
$(element).valid();
},
rules : {
totalRetryCount: { onlyNumbers: true }
},
};
return validation;
};

How to use Javascript to set value of page element from APEX_ITEM

I'm writing some code in Oracle Apex and I don't come from a development background, so pardon my bad code. I'm dynamically generating a form and I want to set a hidden page item when the user changes the value of a specific form element. Here is the code I'm using:
select APEX_ITEM.HIDDEN(2,base_data_seq_nbr)||APEX_ITEM.HIDDEN(6,case when substr(description,0,1)= chr(49838) then substr(description,-(length(description)-1)) else description end)||APEX_ITEM.HIDDEN(7,case when substr(description,0,1)= chr(49838) then 1 else 0 end)||APEX_ITEM.HIDDEN(9,
data_select(replace(replace(trim(substr(field_name,-(length(field_name)-instr(field_name,',',1)))),'BSBR',''),'C','L'), substr(field_name,0,instr(field_name,',',1)-1), :P721_XCASE,:P721_XRETSTAT,:P721_XID,:P721_XCUSNUM,:P721_DB_ID))||case when substr(description,0,1)= chr(49838)
then '<img src="/i/themes/theme_2/images/required.gif" alt="Value Required" alt="Value Required" />'
else null
end as req_ind,
case when substr(description,0,1)= chr(49838)
then substr(description,-(length(description)-1))
else description
end as description,
APEX_ITEM.DATE_POPUP(1,rownum,
to_date(data_select(replace(replace(trim(substr(field_name,-(length(field_name)-instr(field_name,',',1)))),'BSBR',''),'C','L'), substr(field_name,0,instr(field_name,',',1)-1), :P721_XCASE,:P721_XRETSTAT,:P721_XID,:P721_XCUSNUM,:P721_DB_ID),'MM/DD/YYYY'),'MM/DD/YYYY',10,10,'onkeyup="javascript:FormatDate(this);"' ||case when instr(substr(field_name,1,4),'DOB,',1)>0 then ' onchange="javascript:$s(''P721_DOB_RBD'',this);"' end,'datepicker_'||rownum)
end
end as field_format
from bcvsown.bcvs_base_data
inner join v_lookup v
on v.value_seq = stmt_type
left join (select * from apex_collections where collection_name = 'ERR_COLLECTION') ac
on base_data_seq_nbr=ac.n001
where caseno = :P721_XCASE
and v.value_cd = case when :P721_XDE_SEQ > 1 then decode(:P721_XIS_BSRS,'true','BSRS','BET') else v.value_cd end
and db_id = :P721_DB_ID
and v.type_cd = 'STMT_TYPE'
order by base_data_seq_nbr
The page renders as expected with no error and the page source shows the javascript settings (onchange="javascript:$s(''P721_DOB_RBD'',this);") applied only to the elements I am aiming for. But when I change the element, it doesn't seem to set the value of the hidden page item (P721_DOB_RBD).
No offense, that markup is quite horrible. Take the time to properly format and indent your code!
As for your problem, this is the Oracle apex javascript apis reference for $s
$s(pNd, pValue, pDisplayValue, pSuppressChangeEvent)
Given a DOM node or string ID (pNd), this function sets the
Application Express item value taking into account the item type. The
pDisplayValue is optional. If used for a page item of type "Popup LOV"
where the attribute "Input Field" = "Not Enterable, Show Display Value
and Store Return Value", it is used to set the "Input Field". The
value of pValue is stored in the hidden return field. The
pSuppressChangeEvent parameter is optional. Passing either FALSE or
not passing this parameter value results in a change event firing for
the item being set. Pass TRUE to prevent the change event from firing
for the item being set.
Parameters
pNd (DOM Node | string ID)
pValue (String | Array)
pDisplayValue(String)
pSuppressChangeEvent(Boolean)
Passing on this won't work. That will pass on the object, when you want to pass on a value. Since you're creating a APEX_ITEM.DATE_POPUP which will generate an input item, you will need the value of the item at the time the change event happens. You can do that by using $v (ref)
$v(pNd)
Given a DOM node or string ID (pNd), this function returns the value
of an Application Express item in the same format as it would be
posted.
Parameters
pNd (DOM Node | string ID)
So, try with this:
(onchange="javascript:$s(''P721_DOB_RBD'',$v(this));")
Years later - To format the code, use sqldeveloper copy the code to a sqldeveloper sql worksheet,
right click and select format.
SELECT APEX_ITEM.HIDDEN(2,base_data_seq_nbr)
||APEX_ITEM.HIDDEN(6,
CASE
WHEN SUBSTR(description,0,1)= chr(49838)
THEN SUBSTR(description,-(LENGTH(description)-1))
ELSE description
END)
||APEX_ITEM.HIDDEN(7,
CASE
WHEN SUBSTR(description,0,1)= chr(49838)
THEN 1
ELSE 0
END)
||APEX_ITEM.HIDDEN(9, data_select(REPLACE(REPLACE(trim(SUBSTR(field_name,-(LENGTH(field_name)-instr(field_name,',',1)))),'BSBR',''),'C','L'), SUBSTR(field_name,0,instr(field_name,',',1)-1), :P721_XCASE,:P721_XRETSTAT,:P721_XID,:P721_XCUSNUM,:P721_DB_ID))
||
CASE
WHEN SUBSTR(description,0,1)= chr(49838)
THEN '<img src="/i/themes/theme_2/images/required.gif" alt="Value Required" alt="Value Required" />'
ELSE NULL
END AS req_ind,
CASE
WHEN SUBSTR(description,0,1)= chr(49838)
THEN SUBSTR(description,-(LENGTH(description)-1))
ELSE description
END AS description,
APEX_ITEM.DATE_POPUP(1,rownum, to_date(data_select(REPLACE(REPLACE(trim(SUBSTR(field_name,-(LENGTH(field_name)-instr(field_name,',',1)))),'BSBR',''),'C','L'), SUBSTR(field_name,0,instr(field_name,',',1)-1), :P721_XCASE,:P721_XRETSTAT,:P721_XID,:P721_XCUSNUM,:P721_DB_ID),'MM/DD/YYYY'),'MM/DD/YYYY',10,10,'onkeyup="javascript:FormatDate(this);"'
||
CASE
WHEN instr(SUBSTR(field_name,1,4),'DOB,',1)>0
THEN ' onchange="javascript:$s(''P721_DOB_RBD'',this);"'
END,'datepicker_'
||rownum)
END
END AS field_format
FROM bcvsown.bcvs_base_data
INNER JOIN v_lookup v
ON v.value_seq = stmt_type
LEFT JOIN
(SELECT * FROM apex_collections WHERE collection_name = 'ERR_COLLECTION'
) ac
ON base_data_seq_nbr=ac.n001
WHERE caseno = :P721_XCASE
AND v.value_cd =
CASE
WHEN :P721_XDE_SEQ > 1
THEN DECODE(:P721_XIS_BSRS,'true','BSRS','BET')
ELSE v.value_cd
END
AND db_id = :P721_DB_ID
AND v.type_cd = 'STMT_TYPE'
ORDER BY base_data_seq_nbr
If you want to set the value application items in Javascript, there is no way to except one. You can set page level items in Javascript use:
$s(':P12_Item','value');
You can get the page level item value using:
$v('page item')
You can get Application item value in JS using
&APP_ITEM.
But you can't set the value application item in Javascript. You have to create a process which will set application item value and call this process from Javascript apex Ajax.
<script>
var get = new htmldb_Get(null,&APP_ID.,'APPLICATION_PROCESS=SET_APS_CASEIDS',0);
get.addParam('x01',$caseIds);
gReturn = get.get();
if (gReturn) {
window.location='f?p=&APP_ID.:66:&SESSION.::NO:66';
}
</script>
In my case I am setting value in application item using Ajax and process and redirect to other page. That page will use the application item value.
Application process code.
First create Application Item from shared component.
Name: APS_CASEIDS
Session State protection:unrestricted
Create Application Process from shared component.
Name:SET_APS_CASEIDS (Name should be match in ajax call).
Process point:On Demand:run this application process when requested by process.
Process Text:
BEGIN
owa_util.mime_header('text/html', FALSE );
htp.p('Cache-Control: no-cache');
htp.p('Pragma: no-cache');
owa_util.http_header_close;
APEX_UTIL.SET_SESSION_STATE('APS_CASEIDS',APEX_APPLICATION.G_X01);
END;

How can I stop isNaN from returning an error for a blank field?

EDIT:
Ok so I'm updating this question, to show what I've built as I've still not been able to fix this issue. Here is an image of what I've got. So as you can see,
When the user enters a value, the calculation (they are just percentage and total calculations are done "onkeyup". As you can see because of this they return "NaN". Is there a way for me to stop the field displaying a NaN and then subsequently only showing the total values?
I have thought about this and I could just get all the fields to calculate as soon as something is input into the final field? What do you think. Apologies to all those that had perviously answered my question, I am still trying to figure out the best approach, I'm just not as good with JavaScript as I am with HTML/CSS!!
You should try writing a checkNumber function that takes the entered value as its argument (rather than referring directly to each field inside the function). Something like this:
var checkNumber = function (testval) {
if ( isNaN(testval) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
Then bind that function to the keyup event of each form field. There are a number of ways to do this. Look into addEventListener(), or the binding features of a framework like jQuery (.delegate() or .keyup(), e.g.).
Note that if you do bind the function to the event, you won't have to explicitly pass in the value argument. You should be able to work with a field's value within the function via this.value. So you'd have something like this:
var checkNumber = function () {
if ( isNaN( this.value ) ) {
alert('Bad!');
// clean up field? highlight in red? etc.
} else {
// call your calculation function
}
}
And then (with a naive binding approach by ID):
document.getElementById('id_of_a_field').addEventListener('keyup', checkNumber, true);
Can't you just initialize the text box with a default value, say 0?
Why don't you use 3 different functions or an argument to identify which of the inputs the user is pressing? If each of the inputs calls checkNumber(1), checkNumber(2) and checkNumber(3) you can only validate the input that the user is using instead of validating all 3 at the same time.
Alternatively you can use input validation and instead of an alert just return false to prevent the user from inputing invalid chars
How about use short-circuit evaluation with jsFiddle example
EDIT for parseFloat:
function checkNumber()
{
var sInput = parseFloat(document.getElementById('sInput').value || 0);
var dInput = parseFloat(document.getElementById('dInput').value || 0);
var pInput = parseFloat(document.getElementById('pInput').value || 0);
if (isNaN(sInput) || isNaN(dInput) || isNaN(pInput)) {
alert("You entered an invalid character. Please press 'Reset' and enter a number.");
}
}
So if pInput is undefined just use 0, but if the input has value then use that value.
SIDE NOTE: white space is actually a number, +' '; // 0

Categories