Text boxes only char save-reset box - javascript

i want to create 2 text boxes.I want to write something on those text boxes ,and save the value of each in an array or somewhere.There are only char characters.I have and reset to delete a value if it needs.I did a lot work,but it didn't worked.
AM: <input type="text" id="myText" value="GiveAm" size="10" id="myInput">
<button onclick="document.getElementById('myInput').value = ''">Reset</button>
<button onclick="myFunction()">Kataxwrisi</button>
<br>
Surname <input id='charInput' type="text" value="" size="10%">
<button onclick="myFunction()">Kataxwrisi</button>
</br>
<script>
function myFunction() {
document.getElementById("myText").value = "Johnny Bravo";
}
function getChar(event){
if(event.which == null){
return String.fromCharCode(event.keyCode);
}else if(event.which !-0 && event.charCode != 0){
return String.fromCharCode(event.which);
}else{return null; }
}
document.getElementById('charInput').onkeypress=
function(event){
var char =getChar(event || window.event)
if(!char) return false;
document.getElementById('keyData').innerHTML =char + "was clicked";
return true;
}
</script>

Not 100% sure what you are trying to do here. But this is my best guess at a solution. When a user presses the 'enter' key in a text box, the current value of that text box is stored in an array.
var arrSavedValues = [];
function setInputValue(argInputID, argNewValue) {
document.getElementById(argInputID).value = argNewValue;
}
function saveValue(e){
if(e.keyCode === 13){
e.preventDefault();
var caller = e.target || e.srcElement;
arrSavedValues.push(caller.value);
alert("Saved " + caller.value + " to arrSavedValues.");
}
}
<div>
<label>AM:</label>
<input id="txtAM" type="text" value="GiveAm" size="10" onkeypress="saveValue(event)" />
<button onclick="setInputValue('txtAM','')">Reset</button>
<button onclick="setInputValue('txtAM','Johnny Bravo')">Kataxwrisi</button>
</div>
<div>
<label>Surname:</label>
<input id="txtSurname" type="text" value="" size="10" onkeypress="saveValue(event)" />
<button onclick="setInputValue('txtSurname','Johnny Bravo')">Kataxwrisi</button>
</div>

Related

How to prevent form submission if only one out of two paired inputs is filled out

I have a pair of inputs. I have no problem with a user leaving the both of them blank. But what I need is a way to force the user to fill the second input field if he decides to fill the first input field and vice versa(or prevent form submission in the event of that).
Here are my input elements:
<input name="cas[]" id="ca">
<input name="exams[]" id="exam">
<button type="submit" id="submit">Submit</submit>
I would also appreciate if there is also an implementation for multiple input pairs.
A simple script like this should do the trick:
var cas = document.getElementById("ca");
var exams = document.getElementById("exam");
cas.onkeyup = function() {nosubmit()}
exams.onkeyup = function() {nosubmit()}
function nosubmit() {
if ((cas.value != "" && exams.value == "") || (cas.value == "" && exams.value != "")) {
document.getElementById("submit").disabled = true;
} else {
document.getElementById("submit").disabled = false;
}
}
<input name="cas[]" id="ca">
<input name="exams[]" id="exam">
<button type="submit" id="submit">Submit</button>
UPDATE:
For more than one pair if inputs give them a class name instead of (or as well as) an id and then do this:
var cas = document.getElementsByClassName("ca");
var exams = document.getElementsByClassName("exam");
var numOfPairs = cas.length;
window.oninput = function() {
if (nosubmit().includes("d")) {
document.getElementById("submit").disabled = true;
} else {
document.getElementById("submit").disabled = false;
}
}
function nosubmit() {
var check = ""
for (i = 0; i < numOfPairs; i++) {
if ((cas[i].value != "" && exams[i].value == "") || (cas[i].value == "" && exams[i].value != "")) {
check += "d";
} else {
check += "e";
}
}
return check
}
<input value="" name="cas[]" class="ca">
<input value="" name="exams[]" class="exam">
<br><br>
<input value="" name="cas[]" class="ca">
<input value="" name="exams[]" class="exam">
<br><br>
<input value="" name="cas[]" class="ca">
<input value="" name="exams[]" class="exam">
<br><br>
<input value="" name="cas[]" class="ca">
<input value="" name="exams[]" class="exam">
<br><br>
<input value="" name="cas[]" class="ca">
<input value="" name="exams[]" class="exam">
<button type="submit" id="submit">Submit</button>
You can create a custom myXOR function to check whether the two values are different:
// script.js
/**
* Returns true if values are different
*/
function myXOR(a,b) {
return (a || b) && !(a && b);
}
Then call it on the change event for either inputs, so the button is disabled if at any point only one input is filled in.
// page.html
<form id="form">
<input name="cas[]" id="ca">
<input name="exams[]" id="exam">
<button type="submit" id="submit">Submit</button>
</form>
// script.js
// Get elements from DOM
const form = document.querySelector("#form");
const examInput = document.querySelector("#exam");
const caInput = document.querySelector("#ca");
const button = document.querySelector("#submit");
const handleChange = e => {
// !! to cast value to boolean
// Will disable button if values are different, ie. if one input is filled and the other isn't
if(myXOR(!!examInput.value, !!caInput.value)) {
button.disabled = true;
} else {
button.disabled = false;
}
}
// Listen for changes on either input
examInput.addEventListener("change", handleChange);
caInput.addEventListener("change", handleChange);

Webpage reloading in every form submit

I have a problem of page reloading.
HTML
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
Javascript
function commentForm() {
var x = document.getElementById('check').checked;
var y = document.getElementById('text').value;
if (y == null || y == "") {
alert('please enter some value');
return false;
}
if (x == false) {
alert('Please check the checkbox')
return false;
}
else {
document.getElementById('demo').innerHTML += document.getELementById('text').value + "<br>";
return true;
}
}
My problem is that when i submit the page it is reloading instead of copying the text.
Please help me with that.
Try this. I changed the button from a submit input to just a button input so that it only runs the script. You don't want the form to submit, that requires a reload of the page to "submit" the form to the sever. Also you need to get the value from the text input:
document.getElementById('demo').innerHTML += document.getElementById('text').value + "<br>
But since you already put that value into var text you can just reuse that variable. Additionally you weren't checking if if the checkbox was checked because it was looking at the variable x for both inputs. Try running this:
function commentForm() {
var checkBox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkBox) {
alert('Please check the checkbox')
return false;
} else {
document.getElementById('demo').innerHTML += text + "<br>";
return true;
}
}
<form>
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="button" value="Comment" class="txt2" onclick="return commentForm()">
</form>
<p id="demo"></p>
function commentForm() {
var checkbox = document.getElementById('check').checked;
var text = document.getElementById('text').value;
if (!text) {
alert('please enter some value');
return false;
}
if (!checkbox) {
alert('Please check the checkbox');
return false;
}
else {
document.getElementById('demo').innerHTML += text + "<br>";
return false;
}
}
<form onsubmit="return commentForm()">
<input type="text" id="text">
<input type="checkbox" id="check" name="check">
<input type="submit" value="Comment" class="txt2">
</form>
<p id="demo"></p>
If you want the page not to be redirected you can use the return false in the else statement.

Using jQuery to validate checkboxes and input text values

I need your help,
Is there a way one can possible use the all so powerful jQuery to validate the following conditions before enabling button?
If the user inputs a value in the text box and then checks one of the checkboxes, then enable the button
If the user already has a value present in the text, and then checks one of the checkboxes, then enable the button
How can this be written in jQuery, from my perspective this would some lenghty form field checking no?
Here's the HTML markup:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
</body>
</html>
This might get you started. You can make the field validation as complex or simple as you wish.
$('input[type=checkbox]').click(function(){
var tmp = $(this).next('input').val();
//validate tmp, for example:
if (tmp.length > 1){
//alert('Text field has a value');
$('#mybutt').prop('disabled',false);
}else{
//alert('Please provide a long value in text field');
$('#mybutt').prop('disabled', true);
$(this).prop('checked',false);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="mybutt" type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup"><input type="text" id="date3">
Try this way..
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
$('input').on('change input', function() {
$input = $('input');
$button = $('input[type="button"]');
var arr = [];
$input.each(function() {
if ($(this).attr('type') !== 'button') {
arr.push(check($(this)));
arr.indexOf(false) == -1 ? $button.removeAttr('disabled') : $button.attr('disabled', 'disabled');
}
})
})
function check(elem) {
if ($(elem).attr('type') == 'checkbox' && $(elem).is(':checked')) return true;
if ($(elem).attr('type') == 'text' && $(elem).val().trim().length) return true;
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Add To Calendar" disabled>
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date1">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date2">
<br>
<input type="checkbox" name="dategroup">
<input type="text" id="date3">

Confused on ordering of function calls and debugging

I am trying to debug a function call in my JSP program and really confused on the ordering of how things worked. I am using NetBeans. When I run the project in debug mode, it goes into my '$("#searchEFT").mouseup(function ()' function and trace through all of it. 'searchEFT' is a button that I am using to access my servlet. When I process the page and then click the 'searchEFT' button, it hits the function call based on getting the right alert but doesn't trace in the debug. Why is it doing that? Is the first call of the function on load setting up the check when the user does the mouseclick?
This function is outside of the '$(document).ready(function ()' at the top and the function call is after the button declaration in the JSP.
EDIT: here is the JSP code:
<head>
<script>
$(document).ready(function ()
{
$(function ()
{
$("#CMDCreationDate").datepicker({
dateFormat: "yy-mm-dd"
});
});
}) ;
window.onbeforeunload = confirmExit;
function confirmExit()
{
alert("Alert-- leaving this page.");
}
function numbersonly(myfield, e, dec) {
//function to check that only numeric values are entered
var key;
var keychar;
if (window.event)
key = window.event.keyCode;
else if (e)
key = e.which;
else
return true;
keychar = String.fromCharCode(key);
// control keys
if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
return true;
// numbers
else if ((("0123456789").indexOf(keychar) > -1))
return true;
// decimal point jump
else if (dec && (keychar == ".")) {
myfield.form.elements[dec].focus();
return false;
} else
return false;
}
</script>
</head>
<body>
<header>
<?audit suppress oracle.ide.xml.validation-error?>
<div class="floatL appTTL">SAMS - EFT Schedule Number Search/Update Screen</div>
<div id="navWrap">
<nav class="floatR">
<ul>
<li>
Home
</li>
<li>
Search
</li>
<li>
Help
</li>
<li>
Help
</li>
</ul>
</nav>
</div>
<div class="clear"></div>
</header>
<main class="mainWrapper">
<form id="formID" method="POST" action="EFTscreen?action=searchEFT" >
<div class="commandcontainer">
<div id="divBox">
<h1 class="formTTL">Please Enter Schedule Number/Contract Year or either Schedule
Status/Creation Date value</h1>
<label class="labelTTL">Schedule Number</label>
<label class="labelTTL3">Contract Year</label>
<label class="labelTTL3">Status</label>
<label class="labelTTL">Creation Date</label>
<br/>
<input id="CMDScheduleNumber" name="CMDScheduleNumber" type="number" class="textsmall" maxlength="5"
value="${ScheduleNum}" onKeyPress="return numbersonly(this, event)"/>
<input id="CMDContractYear" name="CMDContractYear" type="number" class="textsmall" maxlength="4"
value="${ContractYear}" onKeyPress="return numbersonly(this, event)"/>
<select size="1" id="CMDSchedStatus" name="CMDSchedStatus" class="combosmall">
<c:forEach items="${statusList}" var="current">
<option value="${current}"
<c:if test="${current == Status}"> selected="selected"</c:if>
>${current}</option>
</c:forEach>
</select>
<input id="CMDCreationDate" name="CMDCreationDate" type="text" class="textsmall"
value="${CreationDate}" maxlength="10"/>
<br/>
<button id="searchEFT" class="btn smBtn">Search</button>
</div>
<div id="divButton">
<button id="searchMEFTS" type="submit" formaction="EFTscreen?action=searchMEFTS&screen=mainEFT"
class="btn midBtn">Update Schedule Status</button>
<button id="clearMenu" type="submit" formaction="EFTscreen?action=clearMenu"
class="btn midBtn Space">Return to Menu</button>
</div>
<div id="clear"></div>
</div>
<article class="divBoxdet">
<fmt:formatNumber var="trdettotal" value="${detResults.getTOTAL_AMOUNT()}" pattern="$##,###,##0.00"/>
<label class="labelTTLdet floatL">
Schedule Number
<input id="txtScheduleNumber" type="number" class="textdet"
value="${detResults.getSCHEDULE_NUMBER()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Contract Year
<input id="txtContractYear" type="number" class="textdet"
value="${detResults.getEFT_CONTRACT_YEAR()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Date Created
<input id="txtCreationDate" type="text" class="textdet"
value="${detResults.getCREATION_DATE()}" readonly/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Num of Records
<input id="txtNumRecords" type="number" class="textdet"
value="${detResults.getNUM_OF_PAY_RECORDS()}" readonly/>
</label>
<label class="labelTTLdet floatL">
Status
<br/>
<input id="txtStatus" type="text" class="textdet"
value="${detResults.getSTATUS()}" maxlength="2"/>
</label>
<label class="labelTTLdet floatL">
Status Date
<input id="txtStatusDate" type="text" class="textdet"
value="${detResults.getSTATUS_DATE()}" maxlength="10"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<label class="labelTTLdet floatL">
Schedule Total
<input id="txtScheduleTotal"
type="text" class="textdet" value="${trdettotal}" readonly/>
</label>
<label class="labelTTLdet floatL">
Schedule Post Date
<input id="txtPostDate" type="text" class="textdet"
value="${detResults.getSCHEDULE_POST_DATE()}" maxlength="10"/>
</label>
<label class="labelTTLdet floatL">
Reel Number
<input id="txtReelNumber" type="text" class="textdet"
value="${detResults.getREEL_NUMBER()}" maxlength="8"/>
</label>
<div class="clear"></div>
<br/>
<br/>
<button id="pullMEFTD"
class="btn largeBtn Space floatL">Update Schedule Payment Status</button>
<script>
$("#searchEFT").mouseup(function ()
{
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
var schedLen = Cmd_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Cmd_Contract_Year = $('#CMDContractYear').val();
var yearLen = Cmd_Contract_Year.length;
//var Cmd_Status = document.getElementById("CMDSchedStatus").value;
var Cmd_Status = $('#CMDSchedStatus').val();
var statStr = Cmd_Status.replace(/\s/g, "");
var statLen = statStr.length;
//var Cmd_Creation_Date = document.getElementById("CMDCreationDate").value;
var Cmd_Creation_Date = $('#CMDCreationDate').val();
var createLen = Cmd_Creation_Date.length;
if ((schedLen > 0 && yearLen === 0) || (schedLen === 0 && yearLen > 0))
{
alert("Schedule Number and EFT Contract Year must be both populated");
}
;
if ((statLen === 0) && (createLen === 0) && (schedLen === 0) && (yearLen === 0))
{
var r = confirm("Are you sure you want to pull all EFT schedule numbers?");
if (r === false)
{
alert("Please enter information in any of the command line fields");
return false;
}
else
{
$('#formID').submit();
}
} ;
});
$("#pullMEFTS").mouseup(function ()
{
var Det_Sched_Number = $('#txtScheduleNumber').val();
var detschedLen = Det_Sched_Number.length;
//var Cmd_Contract_Year = document.getElementById("CMDContractYear").value;
var Det_Contract_Year = $('#txtContractYear').val();
var detyearLen = Det.length;
var Det_Status = $('#txtStatus').val();
if (detschedLen > 0)
{
alert("Schedule Number not found. Please investigate");
}
;
if ( holdStatus.matches("RP") ||
holdStatus.matches("VP") ||
holdStatus.matches("CP") )
{
alert("User can only update schedule number in NP status");
}
});
</script>
</article>
</form>
</main>
</body>
Thanks
The line:
$("#searchEFT").mouseup(function ()
is the function call that sets the mouseup handler; it is not the mouseup handler itself.
If you want to break inside the mouseup handler then you need to set a breakpoint somewhere inside the handler function itself, e.g.,
// First executable line of the mouseup handler
var Cmd_Sched_Number = $('#CMDScheduleNumber').val();
Unrelated, but I would break up the handler function into much smaller pieces, roughly:
function getFormData() {
return {
number: $('#CMDScheduleNumber').val().trim(),
year: $('#CMDContractYear').val().trim(),
status: $('#CMDSchedStatus').val().replace(/\s/g, '').trim(),
date: $('#CMDCreationDate').val().trim()
};
}
function invalidNumberAndYear(formData) {
return ((formData.number !== '') && (formData.year === '')) ||
((formData.year !== '') && (formData.number === ''));
}
function isPullAll(formData) {
return formData.number === '' &&
formData.year === '' &&
formData.status === '' &&
formData.date === '';
}
function searchEftMouseup(e) {
e.preventDefault();
var formData = getFormData();
if (invalidNumberAndYear(formData)) {
alert('Schedule Number and EFT Contract Year must be both populated');
return;
}
if (isPullAll(formData)) {
if (confirm('Are you sure you want to pull all EFT schedule numbers?')) {
$('#formID').submit();
} else {
alert('Please enter information in any of the command line fields');
}
}
}
$('#searchEFT').on('mouseup', searchEftMouseup);
This allows small stuff to be thought about easily, and begins to reveal your validation needs, and suggests a shape for your remaining code.
(Most of which, btw, was not relevant to the question–it's good to post only the minimum amount necessary to help people understand the issue :)

Is insertAdjacentHTML problematic?

I have two functions. The first is the one in which all the input elements will be checked to make sure they are filled correctly. Every thing works well but as the second function comes into action ( The second function 'newInput()' adds inputs ) the first function can not be applied anymore.
The debugger says the emailSec in atpositionSec = emailSec.indexOf("#"), is undefined.
Does any body know the solution??
The markup goes here:
<--!The HTML-->
<form method="post" action="" id="cms" name="cms" onSubmit="return error()">
<table>
<tbody id="myInput">
<tr>
<td>
<label>Role:<span> *</span></label>
<input type="text" name="role" id="role" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<label>Email:<span> *</span></label>
<input type="email" name="emailSec" id="emailSec" value="" class="required span3" role="input" aria-required="true" />
</td>
<td>
<button style="height: 20px;" title='Add' onclick='newInput()'></button>
</td>
</tr>
</tbody>
<input type="hidden" name="count" id="count" vale=""/>
</table>
<input type="submit" value="Save Changes" name="submit" id="submitButton" title="Click here!" />
</form>
The First Function:
function error()
{
var emailSec = document.forms['cms']['emailSec'].value,
role = document.forms['cms']['role'].value,
atpositionSec = emailSec.indexOf("#"),
dotpositionSec = emailSec.lastIndexOf(".");
if( topicSec == '' || topicSec == null)
{
alert ("Write your Topic!");
return false;
}
else if(role == '' || role == null)
{
alert ("Enter the Role of the email owner!");
return false;
}
else if(emailSec == '' || emailSec == null || atpositionSec < 1 || dotpositionSec < atpositionSec+2 || dotpositionSec+2 >= emailSec.length)
{
alert ("Enter a valid Email!");
return false;
}
else return true;
}
The Second Function:
//The Javascript - Adding Inputs
var i = 1,
count;
function newInput()
{
document.getElementById("myInput").insertAdjacentHTML( 'beforeEnd', "<tr><td><input type='text' name='role" + i + "' id='role' value='' class='required span3' role='input' aria-required='true' /></td><td><input type='email' name='emailSec" + i + "' id='emailSec' value='' class='required span3' role='input' aria-required='true' /></td><td><button style='height: 20px;' title='Remove' onclick='del(this)'></button></td></tr>");
count = i;
document.forms["cms"]["count"].value = count;
i++;
}
// Removing Inputs
function del(field)
{
--count;
--i;
document.forms["cms"]["count"].value = count;
field.parentNode.parentNode.outerHTML = "";
}
The problem is that after the first addition, document.forms['cms']['emailSec'] becomes an array with all the elements with the name emailSec, so you would need to validate all of them individually using document.forms['cms']['emailSec'][i].
To save you some trouble, you could use the pattern attribute of the input elements in html5 to do this automatically. Furthermore, you could use something like <input type="email" required /> which I think will do almost all the work for you.

Categories