onSubmit validation changing label style - javascript

I'm trying to get this form to change label color after submission if the field is empty and then return back to normal when the field is filled in.
It's behaviour would be something similar to:
Onsubmit validate change background requried fields?
Except I can't figure out how to link the inputs to the labels. I'm using the jsFiddle from the link above at:
http://jsfiddle.net/interdream/cpG2r/7/
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
My JavaScript isn't so good. Please help!

Here is your Working sample</>

You should look around Knockoutjs style binding with dom value.

you could add label tags, like:
<form action="" id="myForm">
<label for="field1">Required field:</label> <input type="text" name="field1" class="required" /><br />
<label for="field2">Required field 2:</label> <input type="text" name="field2" class="required" />
<input type="submit" value="Go" />
</form>
And in js part
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
var lbl = document.getElementsByTagName("label")[i]; //get label
if(!fields[i].value) {
lbl.style.color = "red";
console.log(lbl );
fields[i].style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
lbl.style.color = "black";
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
See : updated Fiddle

Try
<form action="" id="myForm">
<label>Required field: </label><input type="text" class="required" /><br />
<label>Required field 2: </label><input type="text" class="required" />
<input type="submit" value="Go" />
</form>
And
window.onload = function() {
document.getElementById("myForm").onsubmit = function() {
var fields = this.getElementsByClassName("required"),
sendForm = true;
for(var i = 0; i < fields.length; i++) {
if(!fields[i].value) {
fields[i].style.backgroundColor = "#ff0000";
var prev = fields[i].previousSibling;
while(!/label/i.test(prev.tagName)){
prev = prev.previousSibling;
}
prev.style.backgroundColor = "#ff0000";
sendForm = false;
}
else {
fields[i].style.backgroundColor = "#fff";
}
}
if(!sendForm) {
return false;
}
}
}
Demo: Fiddle

You can use jquery validation Plugin ... it has support for all types of validations as well as changing label colors & Can display suitable error messages

Here is very simple, smart yet effective way to doing this by using amazing knockout binding here is working sample :JsFiddle Link
var viewModel = {
validation: ko.observable(function(){})
};

Related

Maintain visibility of a form-textinput when checkbox is checked

In my HTML I have a form, where a user can select the checkbox "other" and a textbox appears. Otherwise the textbox is hidden. Below you can find my code. But if the user selects "other", types in his text und submits the form, the textbox is hidden again-although the checkbox maintain checked (saved in localStorage). I cannot find my mistake here.
Form:
<label class="form-check">
<input class="form-check-input" name="filetype" type="checkbox" id="other" value="" onclick="save()">
<span class="form-check-label"
<input placeholder="e.g. 'msg'" name="other" onsubmit="save();" class="form-control input-lg" type="text" id="otherValue" value="{{extension}}">
</span>
</label> <!-- form-check -->
Visible/Hidden
<!--"Other"-filter-->
<script type="text/javascript">
var otherCheckbox = document.querySelector('input[id="other"]');
var otherText = document.querySelector('input[id="otherValue"]');
otherText.style.visibility = 'hidden';
otherCheckbox.onchange = function(){
if(otherCheckbox.checked) {
otherText.style.visibility = 'visible';
otherCheckbox.value = otherText.value;
save();
} else {
otherText.style.visibility = 'hidden';
}
};
</script>
Tried to solve this Problem by saving the info in the sessionStorage but it still does not work.
<!--Save Checkbox-State-->
<script type="text/javascript">
const checkboxen = [...document.querySelectorAll("[type=checkbox]")].map(inp => inp.id); //list of all checkbox-IDs
function save(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checkbox = document.getElementById(id);
sessionStorage.setItem(id,checkbox.checked);
}
var other = document.getElementById('otherValue');
sessionStorage.setItem('otherValue',other.style.visibility);
}
function load(){
for (var i = 0 ; i< checkboxen.length; i++){
var id = checkboxen[i];
var checked =JSON.parse(sessionStorage.getItem(id));
document.getElementById(id).checked = checked;
}
var other = JSON.parse(sessionStorage.getItem('otherValue'));
document.getElementById('otherValue').style.visibility = other;
}
function deleteCheckbox(){
sessionStorage.clear();
}
</script>
Thanks for any help <3
with prop jquery:
<script>
$(function(){
var other = localStorage.input === 'true'? true: false;
$('input').prop('checked', other);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
console.log($(this).is(':checked'));
});
</script>
this is my solution:
<script type="text/javascript">
var other = document.getElementById('other');
var otherText =document.querySelector('input[id="otherValue"]');
$(document).ready(function(){
if (other.checked){
otherText.style.visibility = 'visible';
otherText.value = "{{extension}}";
other.value = "{{extension}}";
} else {
otherText.style.visibility = 'hidden';
otherText.value = "";
}
});

How to apply a class attribute to an HTML string (not rendered on the document)

I am am developing code for am automator to improve the project with several pages.
I have a textarea input where I can enter HTML and it shows me the HTML with the right structure.
HTML:
<textarea name="message">
<input type="text" value="TextTwo" id="texttwo"/>
<input type="text" value="DataOne" id="dataone"/>
<input type="text" value="NumberTwo" id="numbertwo"/>
<input type="text" value="TextOne" id="textone"/>
<input type="text" value="DataTwo" id="datatwo"/>
<input type="text" value="NumberOne" id="numberone"/>
</textarea>
<button>process</button>
JS/JQuery:
$('button').click(function () {
var code = $('textarea[name=message]').val();
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(code);
});
I would like to apply classes following these rules:
The input that has the word "Text" value in applying the class = "text"
The input that has the word "Data" value in applying the class = "data"
The input that has the word "Number" value in applying the class = "number"
An example of how the code would output in textarea
<input type="text" value="TextTwo" id="texttwo" class="text" />
<input type="text" value="DataOne" id="dataone" class="data" />
<input type="text" value="NumberTwo" id="numbertwo" class="number" />
<input type="text" value="TextOne" id="textone" class="text"/>
<input type="text" value="DataTwo" id="datatwo" class="data" />
<input type="text" value="NumberOne" id="numberone" class="number" />
DEMO CODE
What is a good approach to do this using JQuery?
I updated your fiddle and had this code working -- Can't give you a link since I don't actually have a fiddle account:
$('button').click(function () {
var code = $('textarea[name=message]').val();
// The best thing to do here is to turn that string of HTML into
// DOM elements and let the browser do the work.
var elms = jQuery.parseHTML(code);
var result = "";
// Now that we've processed the HTML into an array, work with it.
for (var i = 0; i < elms.length; i++) {
var el = elms[i];
if (el.tagName && el.tagName.toLowerCase() === "input") {
// Great! We we have an 'input' element.
var val = el.value;
if (val.indexOf("Text") !== -1) {
el.className = "text";
}
if (val.indexOf("Data") !== -1) {
el.className = "data";
}
if (val.indexOf("Number") !== -1) {
el.className = "number";
}
}
if (el.nodeType === 3) {
// Handle text nodes
result += el.nodeValue;
} else {
result += el.outerHTML;
}
}
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(result);
});
Under the assumption that all the html in the textarea is valid, What we can do is just build the html into a div and then format the html with jQuery. After this is done just get the content and put it in the textarea.
$('button').click(function () {
var code = $('textarea[name=message]').val(),
$code = $('<div />').html(code),
classes = {'Text': 'text', 'Data': 'data', 'Number': 'number'};
if ($('#output').length < 1) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('input', $code).each(function(){
var t = this,
$t = $(this);
for(key in classes){
if(t.value.indexOf(key) > -1){
$t.addClass(classes[key]);
return;
}
}
});
$('#output').val($code.html());
});
http://jsfiddle.net/LC5y3/4/
DEMO
$('button').click(function () {
var code = $.parseHTML($('textarea[name=message]').val());
console.log(code);
var newCode = "";
code = $.grep(code, function (n, i) {
if (n.nodeValue) {
return n.nodeValue.trim()
} else {
return (n.outerHTML && n.outerHTML.trim())
}
});
for (var i = 0; i < code.length; i++) {
var element=$(code[i]);
element.addClass(element.attr("type"));
newCode += code[i].outerHTML;
}
console.log(newCode);
console.log(code);
if (!$('#output').length) {
$("body").append('<h2>Output</h2><textarea id="output" rows="10" cols="100"></textarea>');
}
$('#output').val(newCode);
});
You can use the attribute contains selector.
jsFiddle
$('input[id*="text"]').addClass('text');
$('input[id*="number"]').addClass('number');
$('input[id*="data"]').addClass('data');
You can dynamically build the elements:
$('input').addClass('className').attr('value','number');

Check,reset buttons active after all inputs were completed

how can i make check and reset buttons active after 6 inputs were completed? I have tryed:
if($('.input') == ""){
checkBtn.disabled = true;
resetBtn.disabled = true;
}
else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
EDIT 2 with fiddle : http://jsfiddle.net/usPMd/88/
Edit : Your Jsfiddle return error 404... So I developed a basic example (it is not perfect).
Jsfiddle
Javascript solution :
<body>
<form>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input type="text" onChange="checkInput()" onKeyup="checkInput()"/>
<input id="send" type="submit" disabled/>
<input id="reset" type="reset" disabled/>
</form>
<script type="text/javascript">
var checkBtn = document.getElementById("send");
var resetBtn = document.getElementById("reset");
var inputTag, lengthInputTag, nbCompleted;
function forEach( a, fn ) {
return [].forEach.call(a, fn);
};
function checkInput(){
inputTag = document.getElementsByTagName("input");
lengthInputTag = inputTag.length;
nbCompleted = 0;
console.log(inputTag);
forEach(inputTag, function(el) {
if(el.value != ""){
nbCompleted++;
}
});
if(nbCompleted < 6){
checkBtn.disabled = true;
resetBtn.disabled = true;
}else{
checkBtn.disabled = false;
resetBtn.disabled = false;
}
};
</script>
</body>
if($('.input').length == 6){
checkBtn.disabled = false;
resetBtn.disabled = false;
}else{
checkBtn.disabled = true;
resetBtn.disabled = true;
}
So, use length then:
if($('.input').length == 7){ //after 6 is 7th input
checkBtn.disabled = true;
resetBtn.disabled = true;
}
And also there might be a typo .input should be input but not 100% sure because this might also be class.
Ok, Here you go:
Workign demo: JSFiddle
HTML (partial):
<button id="validateButton" class="validateButton" type="button" disabled="disabled">Check</button>
<button id="resetButton" class="resetButton" type="button" disabled="disabled">Reset</button>
JS:
$(document).on('change blur', '.input', function(){
var count = 0;
$('.input').each(function(){
var elem_v = $.trim ( $(this).val() );
if (elem_v != "") {
count++;
}
})
$('button').prop('disabled', true);
if (count===6){
$('button').prop('disabled', false);
}
});

Form redirect on checkbox selection

Here's what i'm trying to achieve: I want to create a HTML page with a form, when you submit the form it goes to 1 of 4 locations. There is a default hidden main option thats auto-selected on page load and 2 sub-options that are optional.
Oh, and it calculates the amounts on selection!
Here's my code so far:
<html>
<head></head>
<body>
<form onSubmit="submitForm();" id="myForm" type="get">
<input id="myCheckbox1" name="myCheckbox1" type="checkbox" value="20" onClick="calcNow();" />Default option<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="30" onClick="calcNow();" />Add-on option 1<br/>
<input id="myCheckbox2" name="myCheckbox2" type="checkbox" value="40" onClick="calcNow();" />Add-on option 2<br/>
<input id="myTotal" name="myTotal" type="text" value="" disabled="disabled" /><br/>
<input type="button" id="myButton" onClick="submitForm();" value="Continue" />
</form>
<script type="text/javascript">
var pages = [[["http://mysite.com/page1.html"],["http://mysite.com/page2.html"],["http://mysite.com/page3.html","http://mysite.com/page4.html"]]];
function calcNow()
{
var cb = document.getElementById("myCheckbox1");
var cb = document.getElementById("myCheckbox2");
var cost1 = cb.checked ? parseInt(cb.value) : 0;
var cost2 = cb.checked ? parseInt(cb.value) : 0;
var costTotal = cost1 + cost2;
document.getElementById("myTotal").value = costTotal;
var op1 = cb.checked ? 1 : 0;
if (op1 != undefined)
{
return pages[op1];
}
return undefined;
}
function submitForm()
{
var page = calcNow();
if (page != undefined)
{
alert(page);
// ---- To navigate ----
//location.href = page;
// ---- To alter post ----
//var form = document.getElementById("myForm");
//form.action = page;
//form.submit();
}
else
{
alert("Please answer all questions.");
}
}
function getRadioValue(name)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].value);
}
}
return 0;
}
function getRadioData(name, attribute)
{
var controls = document.getElementsByName(name);
for (var i = 0; i < controls.length; i++) {
if (controls[i].checked) {
return parseInt(controls[i].dataset[attribute]);
}
}
return undefined;
}
</script>
</body>
</html>
Try this
EDIT:
function submitForm()
{
//The code goes inside here, you have to decide where to redirect from if or the else
window.location.assign("http://www.w3schools.com/");
var page = calcNow();
if (page != undefined)
{
alert(page);
}
else
{
alert("Please answer all questions.");
}
}

I have an issue to create dynamic fields with string count using Javascript OR Jquery

I have an issue to create dynamic fields with string count using JavaScript or jQuery.
Briefing
I want to create dynamic fields with the help of sting count, for example when I write some text on player textfield like this p1,p2,p3 they create three file fields on dynamicDiv or when I remove some text on player textfield like this p1,p2 in same time they create only two file fields that's all.
The whole scenario depend on keyup event
Code:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
function commasperatedCount(){
var cs_count = $('#player').val();
var fields = cs_count.split(/,/);
var fieldsCount = fields.length;
for(var i=1;i<=fieldsCount;i++){
var element = document.createElement("input");
element.setAttribute("type", 'file');
element.setAttribute("value", '');
element.setAttribute("name", 'file_'+i);
var foo = document.getElementById("dynamicDiv");
foo.appendChild(element);
}
}
</script>
<form>
<label>CountPlayerData</label>
<input type="text" name="player" id="player" onkeyup="return commasperatedCount();" autocomplete="off" />
<div id="dynamicDiv"></div>
<input type="submit" />
</form>
var seed = false,
c = 0,
deleted = false;
$('#player').on('keyup', function(e) {
var val = this.value;
if ($.trim(this.value)) {
if (e.which == 188) {
seed = false;
}
if (e.which == 8 || e.which == 46) {
var commaCount = val.split(/,/g).length - 1;
if (commaCount < c - 1) {
deleted = true;
}
}
commasperatedCount();
} else {
c = 0;
deleted = false;
seed = false;
$('#dynamicDiv').empty();
}
});
function commasperatedCount() {
if (deleted) {
$('#dynamicDiv input:last').remove();
deleted = false;
c--;
return false;
}
if (!seed) {
c++;
var fields = '<input value="" type="file" name="file_' + c + '">';
$('#dynamicDiv').append(fields);
seed = true;
}
}​
DEMO
<script>
function create(playerList) {
try {
var player = playerList.split(/,/);
} catch(err) {
//
return false;
}
var str = "";
for(var i=0; i<player.length; i++) {
str += '<input type="file" id="player-' + i + '" name="players[]" />';
//you wont need id unless you are thinking of javascript validations here
}
if(playerList=="") {str="";} // just in case text field is empty ...
document.getElementById("dynamicDiv").innerHTML = str;
}
</script>
<input id="playerList" onKeyUp="create(this.value);" /><!-- change event can also be used here -->
<form>
<div id="dynamicDiv"></div>
</form>

Categories

Resources