html form 2 fields unique values required - php

I have a html form which has around 10 fields. 2 of those fields must have unique values.
So if I've got:
Name
Date of Birth
Email Address
Current City
Phone Number
Favourite City << Must be unique compared to City Born
City Born << Must be unique compared to Favourite City
Favourite Colour
Favourite Flower
Favourite Animal
I've found the below for validation, but that applies to all form fields. I just need to apply the 'unique' requirement to these two fields...it'd be okay for 'Favourite City' and 'Current City' to have the same values.
Thanks.
var frm = document.querySelector('form.classesName');
var inputs = frm.querySelectorAll('input[type=text]');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var classArr = [];
for(var i = 0; i < inputs.length; i++) {
if(classArr.indexOf(inputs[i].value) != -1) {
inputs[i].style.backgroundColor = "red";
return false;
}
else
classArr.push(inputs[i].value);
}
frm.submit();
});
for(var j = 0; j < inputs.length; j++) {
inputs[j].addEventListener('focus', function() {
this.style.backgroundColor = "white";
});
}
https://jsfiddle.net/samuraii/70nkhthc/

Going off of the JavaScript you posted, and making some assumptions regarding the HTML make up of your form, would something like this work out?
var frm = document.querySelector('form.classesName');
frm.addEventListener('submit', function(e) {
e.preventDefault();
var favoriteCity = document.querySelector('input[name="favoriteCity"]');
var cityBorn = document.querySelector('input[name="cityBorn"]');
if ( favoriteCity.value === cityBorn.value ) {
alert("The City Where One Was Born Can't Be Their Favorite City... ?");
return false;
}
frm.submit();
});
<form class='classesName'>
<input type='text' name='favoriteCity' placeholder='Favorite City'>
<input type='text' name='cityBorn' placeholder='City Born'>
<input type='submit' value'Submit Form'>
</form>

Related

Autocomplete Box Only Shows First Letter

I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>

Get drop down list options based on selected checkbox value

I have the following codes that generate checkboxes from database
< table class="table">
< thead>
< /thead>
< th>
<?php
$oaNamesQuery = "SELECT DISTINCT oaName FROM oaDetails";
$oaNamesQueryExecute = mysqli_query($conn, $oaNamesQuery);
while($oaNamesQueryRow = mysqli_fetch_array($oaNamesQueryExecute)){
$oaName = $oaNamesQueryRow['oaName'];
echo '<div class = "checkbox-group" required style="float:left; margin-right: 25px;"> <input class="checkBoxes" type="checkbox" id="checkBoxArray" name="checkBoxArray[]" value="'.$oaName.'"> '.$oaName.'</div>';
}
?>
< /th>
< /table>
There is another input box as below whereby input type is number
<div class="col-sm">
<label for="numberOfShiftPerDay">Number</label>
<input type="number" class="form-control" id="numberOfShiftPerDay" name="numberOfShiftPerDay" placeholder="No: " onchange="disablingRoutine()" min="1" max="4">
</div>
Example UI as below
When I enter some number, there will be a drop down menu appear according to the number I entered. Eg: If keyed in 1, there will be one drop down list will appear as below using jQuery 'OnChange'. The UI will be as below
What I Need
I need the drop down menu options to be based on user selected checkboxes. Eg: If the user selected checkboxes X, Y and XX, then these drop down list should show X, Y and XX. Can someone help me how to do this?
Edit 1
Added Javascript function on the change routine as suggested by stackoverflow member. But now having duplicate issues. Below the code that I changed
if ($("#numberOfShiftPerDay").val() == 1) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift1').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 2) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift2').append('<option>' + cval + '</option>')
});
} else if ($("#numberOfShiftPerDay").val() == 3) {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift3').append('<option>' + cval + '</option>')
});
} else {
$.each($("input[name='checkBoxArray[]']:checked"), function() {
cval = $(this).val();
$('#oaInShift4').append('<option>' + cval + '</option>')
});
}
You can get the selected checkbox values and append to your dropdown list in your onchange function.
Try this:
function disablingRoutine()
{
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
$('#dropdownID').append('<option>'+cval+'</option>')
});
}
Edit 2
function disablingRoutine()
{
cdata = '';
$.each($("input[name='checkBoxArray[]']:checked"), function(){
cval = $(this).val();
cdata += '<option>'+cval+'</option>';
});
$('#dropdownID').html(cdata)
}

Is there any way that the first character of a text box is either '+' or '-' by default

I have a text field on my form actually its like GMT time. I want the users to
enter integers like '+5' '+6' or '-6' or '-5' etc.
I want to make it easy for users so that they don't have to write '+' or '-' by there self. There should be by default option of '+' or '-' as first character in text field.
I saw some solutions like making a simple drop down in front and user can select from there which will automatically appear in text box.
But i want to make it more easy if some other easy solution is there.
will prefer using HTML5 but if not than jquery will be fine..
Try this one:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
var num = 0;
$('#txt1').keydown(function(e){
num += 1;
if (e.keyCode > 36 && e.keyCode < 41) {
if(num % 2){
$('#txt1').val('+');
}else{
$('#txt1').val('-');
}
}
});
});
</script>
<input type="text" name="txt1" id="txt1" />
you could try this:
var $input = $('#input');
var defaultChar = '+';
$input.val(defaultChar);
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
here is the fiddle
EDIT: added dropdown to select defaultChar.
Javascript:
var $input = $('#input');
var $defaultCharElem = $('#defaultChar');
var defaultChar = $defaultCharElem.val();
$input.val(defaultChar);
$defaultCharElem.on('change', function() {
var $this = $(this);
defaultChar = $this.val();
$input.val(defaultChar + getDigits($input.val()));
});
$input.on('keyup', function(event) {
var $this = $(this);
var currentText = $this.val();
currentText = getDigits(currentText);
$this.val(defaultChar + currentText);
});
function getDigits(text) {
var digits = text.match(/[+-]?(\d*)/);
console.log("text = " + text);
console.log("digits = " + JSON.stringify(digits));
if(digits.length > 1) {
return digits[1];
} else {
return 'did not contain numbers';
}
}
HTML:
<select id="defaultChar">
<option value="+">+</option>
<option value="-">-</option>
</select>
<input type="text" id="input" value="" />
Here is the new fiddle

I can not take all the arrays for serialize jquery

I have a page that has three checkbox lists, the three are dynamically generated
what I want and that as the User is clicking the checkbox values ​​are passed via post, but I only managed to catch Esto values ​​of the first list
I did the code like this:
$("body").find(".fcID").click(function(){
// var v = $(this).val();
//alert(v);
var form = jQuery('#form');
valor = form.serialize();
$.ajax({
type : "POST",
url:"biblioteca/filtra.php",
data: valor,
success: function(data){
$("#tabelafiltro").html(data);
}
});
in html, I put a form with the id of her form and name the form
within that form, I have the checkboxes, so:
<form name="form" id="form" action="" method="post">
<table>
<tr>
<td><input type="checkbox" class="fcID" value="<?php echo $linha['fm-cod-com'] ?>" name="fcID[]"/></td>
</tr>
</table>
<table>
<tr>
<td><input type="checkbox" class="fcID" name="fam[]" value="<?php echo $linha['fm-codigo'] ?>" /></td>
</tr>
</table>
</form>
and the php:
$id = $_POST['fcID'];
$fam = $_POST['fam'];
echo(count($fam)) . " + " . count($id);
somebody help me?
Your code is correct, are u sure that the fam[] checkboxes are checked? Checkboxes will serialize only if they have atribute checked="checked".
Unfortunately the "name" is not converted to an array by jQuery.. so instead of this:
echo $_POST['fcID'][0]; // undefined
you have this
echo $_POST['fcID[]']; // expected value
I created the following. It has some limitations, but should do what you want. I appreciate if you can rate my answer.
var form = jQuery('#form');
valor = form.formToObj();
// formToObj (c) 2012 Frank Forte.
// Please contact me for a free license to use on personal or business website
// #frankforte or frank # interactinet .com!
jQuery.fn.formToObj = function()
{
var obj = {}
jQuery("input,select,textarea",this).each(function(){
if(jQuery(this).attr("disabled")){
return;
}
var n = jQuery(this).attr("name") || jQuery(this).attr("id")
var v = jQuery(this).val();
// e.g.<input name="test[one][two][three]" value="hello world">
if(!n.match(/\[/))
{
obj[n] = v
}
else
{
// get keys of array, e.g. "one","two","three"
var keys = []
nkeys= n.split('[')
var i = 0;
for(k in nkeys)
{
if(i > 0)
{
var nk = nkeys[k]
if(typeof nk == "string")
{
if(nk.match(/\]/))
{
nk = nk.replace("]","")
}
keys.push(nk);
}
}
i++
}
// name e.g. "test"
n = n.replace(/^([^\[\]]+)\[.*$/i,"$1");
// create object and add value then array keys from bottom up
var iobj = {}
for(i = keys.length; i > 0; i--)
{
j = i-1;
var k = keys[j]
if(k==""){k = 0;}
if(i == keys.length)
{
iobj[k] = v
}
else
{
iobj[k] = iobj
}
}
// Need to start with obj[n] and add new values under appropriate keys
// prevents unsetting or overwriting keys deeper than n
if(typeof obj[n] == "undefined")
{
obj[n] = {}
}
obj[n][k] = iobj[k]
}
})
return obj
}

Writing a summarized validation javascript code

I have an HTML page on the admin site for managing user on a HTML/Javascript/PHP system that runs on browsers. I have close to 20 inputboxes because on one page i have combined several forms of new_user, forgot_password, Change_password and Edit_user_details.
This code is what i used to check the username's empty field, this means i have to write 20 of this lines;
My concern is--> How do i write a short, summarized but effective javascript code to check on empty fields. (I will also need to validate fields like digits, numbers, length, emails etc)
function RequiredFields(){
var username=document.forms["login"]["username"].value;
if (username==""||username==null){
alert("empty username")
document.login.username.focus();
if(document.all||document.getElementById){
document.login.username.style.background="pink";
}
return false;
}
}
You can use jQuery to check for empty fields, have a look at this code:
function Validate() {
$('form input[type="text"]').each(function(){
if (this.value=="")
alert('Value Required');
});
}
To validate things like emails, numbers etc, you would need to write a separate function for those particular text boxes.
See here: http://jsfiddle.net/TgCbB/1/
HTML
<input type="text" id="username" class="required" data-default="User Name"/>
<input type="text" id="email" class="required email" data-default="Email"/>
<input type="text" id="digits" class="required digits" data-default="Integer"/>
The important thing to note here is the class attribute, which indicates how it should be validated. (You could do this with a data- attribute, which would be better, but I used class for backwards compatibility).
You can now, with plain javascript, validate like so:
function validate(e){
var invalid = [];
var required = document.getElementsByClassName("required");
for (var i = 0; i < required.length; i++){
var req = required[i];
var val = req.value || "";
var def = req.hasAttribute("data-default") ? req.getAttribute("data-default") : "";
if (val == "" || val == def)
invalid.push(req);
req.className = req.className.replace(" invalid","");
}
var digits = document.getElementsByClassName("digits");
for (var i = 0; i < digits.length; i++){
var dig = digits[i];
var val = Number(dig.value || "");
var rem = val - Math.floor(val);
if (rem != 0)
invalid.push(dig);
dig.className = dig.className.replace(" invalid","");
}
var emails = document.getElementsByClassName("email"),
reg = /^\w+#[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/;
for (var i = 0; i < emails.length; i++){
var em = emails[i];
var val = em.value || "";
if (!reg.test(val))
invalid.push(em);
em.className = em.className.replace(" invalid", "");
}
for (var i = 0; i < invalid.length; i++){
var inp = invalid[i];
var cls = inp.className.replace(" invalid", "");
inp.className = cls + " invalid";
}
}
Note that the could be made less verbose, but I opted for readability. The concept is, get each item with the class name we're validating against, iterate over them, and then mark it as invalid if it doesn't pass validation.

Categories