I want to make validation for my input text form, that user cannot go further unless all input forms will be completed. i want to make it through every input that even if first is completed, user needs to complete another 2 etc. but at this moment i am only able to make it through the first one and have no idea how to iterate it through every input text.
My html:
<div class="write-to-us">
<div class="col-md-12 field">
<p>Write to us</p>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Name</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your Name</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label>Surname</label>
<input type="text" name="subject" class="my-text-input">
<div class="label-error">Write your surname</div>
</div>
</div>
<div class="col-md-12 field">
<div class="my-form">
<label">Question</label>
<textarea type="text" name="subject" class="my-text-input"></textarea>
</div>
</div>
<div>
<button class="my-button">Check it</button>
</div>
</div>
And my js code for iteration:
myFunction: function() {
var $formField = $('.write-to-us');
if (!$formField.exists()) {
return;
}
initValidation();
function initValidation() {
var errorMsg = $formField.find('.label-error');
var button = $formField.find('.my-button');
var input = $formField.find('input');
var inputContainer = $formField.find('.my-form')
button.click(function(event) {
if(!input.val().trim()) {
errorMsg.css('visibility', 'visible');
inputContainer.addClass('error');
event.preventDefault();
}
});
},
I guess that problem is with .find and should be some jQuery .each but i have no idea how to change it.
I would try doing something like this rather than find.
function initValidation() {
$('.my-button').click(function(){
$("input").each(function() {
var element = $(this);
if (element.val() == "") {
element.closest('.label-error').css('visibility', 'visible');
element.closest('.my-form').addClass('error');
}
});
});
}
Related
I have a select with 3 options and a liveSearch. If the users type an input in the liveSearch-box which doesn't exist as an option, I get the result "No results matched xy". But I want to know, what the user wrote. How do I get his input?
<body class="inventorypage" onload="selectM()">
.....
<form>
<div class="form-row">
<div class="col-lg-7">
<div class="select_box">
<select class="select4 col-md-12" single title="Auswählen" id="searchInput">
<option>Search1</option>
<option>Search2</option>
<option>Search3</option>
</select>
</div>
</div>
</div>
<div class="form-row">
<div class="col-lg-7">
<button type="button" onclick="searchM()" class="btn3 mt-2 mb-3">Search</button>
</div>
</div>
<div class="form-row">
<div>
<p id='output'></p>
</div>
</div>
</form>
function selectM(){
var eingabe = document.getElementById('searchInput');
$(document).ready(function(){
$('.select4').selectpicker({
liveSearch: true
//,noneResultsText: 'I found no results'
});
})
}
function searchM(){
//console.log("users input");
}
The select picker creates a search input box with the class name bs-searchbox. You can get the value by following the code.
$(document).on('keyup', '.select4 .bs-searchbox input', function(e) {
alert($(this).val());
});
I have a form and when the user clicks submit, I would like the form to hide and a thank you message to appear. Unfortunately with the code I have, it's not working and I can't figure out why. I think it might be something with the jQuery so I'd like to try and re-write this function using vanilla JS, but I'm not sure how.
It is the last part of the function, the if (empty.length), hide form, show thank you message that is causing me problems. Everything else is working fine, so its this function I would like to try and write in JavaScript, or try another way using jquery to make it work. The problem is it doesn't work in my code, but when I open this in a jsfiddle, it doesnt just hide the form it opens a new page and I get an error. I don't want the user to be directed to a new page, I just want the form to close and thank-you message to appear. I am very new to this so I apologize if my code is messy.
UPDATE: I really think the issue here is the jQuery, can I write this in plain JS and would that fix it?
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
})
var $form = $('#signup-form'),
$signupForm = $('.form-show'),
$formReplace = $('#thank-you');
$formReplace.hide();
$form.on('submit', function() {
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if (empty.length <= 0) {
$signupForm.hide();
$formReplace.show();
} else {
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="click-subscribe">Show / hide form</button>
<div id="subscribe-content">
<div class="subscription-signup">
<div class="subscription-close" id="subscription-close"></div>
<div class="email-signup">
<p class="cat-title subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<p class="subscription-text">lorem ipsum</p>
<div class="subscription-form">
<form id="signup-form" class="form-show" name="signup-form" method="post" action="${URLUtils.url('Newsletter-SubscribeMobile')}">
<div class="form-row salutation header">
<label for="salutation">Title</label>
<div class="chzn-row valid salutation">
<select id="title" name="title" class="chzn-global-select input-select optional required">
<option value="">--</option>
<option value="Mr">Mr.</option>
<option value="Mrs">Mrs.</option>
<option value="Ms">Ms.</option>
<option value="Miss">Miss</option>
</select>
</div>
</div>
<div class="form-row required">
<label for="firstname">
<span aria-required="true">First Name</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="firstname" type="text" name="firstname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="lastname">
<span aria-required="true">Surname</span>
<span class="required-indicator">*</span>
</label>
<input class="input-text required" id="lastname" type="text" name="lastname" value="" maxlength="500" autocomplete="off">
</div>
<div class="form-row required">
<label for="signup-email" style="display:none;">Email</label>
<input class="header-signup-email" type="text" id="signup-email-header" name="signup-email" value="" placeholder="Email" />
</div>
<div class="form-row text-center">
<input type="submit" name="signup-submit" id="signup-submit" class="subscribe-submit" value="Submit" />
</div>
</form>
<div id="thank-you">
<p>Thanks for subscribing!</p>
</div>
</div>
</div>
</div>
</div>
I think some other javascript/jQuery code are making issues to run the codes, for simple solution make your code as plugin and called it like following.
create new js file called validation.js
(function($){
$.fn.validation = function(){
var $subscribe = $('#click-subscribe');
var $subscribeContent = $('#subscribe-content');
var $subscribeClose = $('#subscription-close');
$subscribeContent.hide();
$subscribe.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
$subscribeClose.on('click', function(e) {
e.preventDefault();
$subscribeContent.slideToggle();
});
var $form = $('#signup-form'), $signupForm = $('.form-show'), $formReplace = $('#thank-you'); $formReplace.hide();
this.on('submit', function(e){
var empty = $(this).find("input, select, textarea").filter(function() {
return this.value === "";
});
if(empty.length == 0){
$signupForm.hide();
$formReplace.show();
}
e.preventDefault();
});
};
})(jQuery);
Now, call the validation.js at the head like below
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="validation.js"></script>
<script type="text/javascript">
$(function(){
$('#signup-form').validation();
});
</script>
I am working with a django project, and part of the requirement is to have a button on the html page which when clicked clones a particular div and appends it to the bottom of the page as shown in the screenshot:
Screenshot of the Page
I was successful in doing this applying the following code:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find('input:text').val('') //Clear the Input fields of the cloned DIV
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:0px;clear:both"></div>
<div style="float:right">
<span class="label label-primary" id="add_cp_button" style="cursor: pointer;" onclick="addVL()">+ Add VL </span>
</div>
<div style="height:0px;clear:both"></div>
<div>
<div id="ext_int_div_1">
<div class="section">
<fieldset class="scheduler-border">
<legend class="scheduler-border">External Interface 1</legend>
<div class="sectionContent" style="border:0px solid grey;width:75%">
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Name</label>
</div>
<div class="col-sm-8">
<input type="text" class="form-control" name="vl_name_1" id="vl_name_1" placeholder="Name"/>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connectivity Type</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_connectivity_type_1" id="vl_connectivity_type_1">
<option value="VIRTIO">VIRTIO</option>
<option value="">None</option>
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
<div class="form-group">
<div class="col-sm-4">
<label>Connection point Ref</label>
</div>
<div class="col-sm-8">
<select class="form-control" name="vl_con_ref_1" id="vl_con_ref_1" />
</select>
</div>
</div>
<div style="height:15px;clear:both"></div>
</div>
</fieldset>
<div style="height:2px;clear:both;"></div>
</div>
</div>
</div>
<input type="hidden" name="vl_count" id="vl_count" value="1" />
Now i have a new issue, i need to make sure that the ID's of the elements withing the DIV are unique too, for example the the ID = "vl_name_1" for the first input box must be changed to "vl_name_2" when creating the creating the clone.
I tried the following example and added the snipped within my addVL() function just to see if any changes happen to my div's:
$("#ext_int_div_1").clone(false).find("*[id]").andSelf().each(function() { $(this).attr("id", $(this).attr("id") + clone.id); });
However, the above code got me nothing ( i am pretty sure the above piece of code is rubbish since i have no clue what it is doing).
Help appreciated here.
Thank you
I hope the snippet below helps.
$(document).ready(function () {
$sharerCount = 1;
$('#addSharer').click(function() {
if($sharerCount < 5) {
$('#sharer_0').clone().attr('id', 'sharer_' + $sharerCount).insertAfter('.sharers:last').find("*[id]").attr('id', 'input_' + $sharerCount).val("").clone().end();
$sharerCount += 1;
}
else {
$('#addSharer').prop('disabled', 'true');
}
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="form">
<div class="form-group">
<label class="control-label col-sm-3 col-xs-12">Share With<span class="red-text">*</span></label>
<div class="col-sm-9 col-xs-12">
<div id="sharer_0" class="field-group sharers">
<input id="input_0" type="text" class="form-control field-sm">
</div>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9 col-xs-12">
<button id="addSharer" type="button" class="btn btn-success">Add Another</button>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
I did the following and solved my problem:
var vl_cnt =1; //Initial Count
var original_external_int_div = document.getElementById('ext_int_div_1'); //Div to Clone
function addVL(){
var clone = original_external_int_div.cloneNode(true); // "deep" clone
clone.id = "ext_int_div_" + ++vl_cnt; // there can only be one element with an ID
original_external_int_div.parentNode.append(clone);
var cloneNode = document.getElementById(clone.id).children[0].firstElementChild.firstElementChild;
cloneNode.innerText = "External Interface "+vl_cnt; //Change the Header of the Cloned DIV
$(clone).find("*[id]").each(function(){
$(this).val('');
var tID = $(this).attr("id");
var idArray = tID.split("_");
var idArrayLength = idArray.length;
var newId = tID.replace(idArray[idArrayLength-1], vl_cnt);
$(this).attr('id', newId);
});
document.getElementById("vl_count").value = vl_cnt; //Keep track of the number of div being cloned
window.scrollTo(0,document.body.scrollHeight);
Thank you #ProblemChild for giving me the pointer in the right direction, I cannot upvote #ProblemChild for providing partial solution.
I have save method on modal window once user execute save method i want to clear the form fields, I have implemented $setPristine after save but its not clearing the form. How to achieve that task using angularJS ?
So far tried code....
main.html
<div>
<form name="addRiskForm" novalidate ng-controller="TopRiskCtrl" class="border-box-sizing">
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="topRiskName" class="required col-md-4">Top Risk Name:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="topRiskName" ng-model="topRiskDTO.topRiskName"
name="topRiskName" required>
<p class="text-danger" ng-show="addRiskForm.topRiskName.$touched && addRiskForm.topRiskName.$error.required">Top risk Name is required field</p>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12">
<label for="issuePltfLookUpCode" class="col-md-4">Corresponing Issue Platform:</label>
<div class="col-md-8">
<select
kendo-drop-down-list
data-text-field="'text'"
data-value-field="'id'" name="issuePltfLookUpCode"
k-option-label="'Select'"
ng-model="topRiskDTO.issuePltfLookUpCode"
k-data-source="issuePltDataSource"
id="issuePltfLookUpCode">
</select>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 fieldHeight">
<label for="issueNo" class="col-md-4">Issue/Risk Number:</label>
<div class="col-md-8">
<input type="text" class="form-control" id="issueNo" ng-model="topRiskDTO.issueNo"
name="issueNo">
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-primary pull-right" ng-disabled="addRiskForm.$invalid" ng-click="submit()">Save</button>
<button class="btn btn-primary pull-right" ng-click="handleCancel">Cancel</button>
</div>
</form>
</div>
main.js
$scope.$on('addTopRisk', function (s,id){
$scope.riskAssessmentDTO.riskAssessmentKey = id;
$scope.viewTopRiskWin.open().center();
$scope.submit = function(){
rcsaAssessmentFactory.saveTopRisk($scope.topRiskDTO,id).then(function(){
$scope.viewTopRiskWin.close();
$scope.$emit('refreshTopRiskGrid');
$scope.addRiskForm.$setPristine();
});
};
});
Hey interesting question and I have messed around with it and I have come up with something like this (I have abstracted the problem and simplified it, it is up to you to implent it to your likings). Likely not super elegant but it does the job: Fiddle
<div ng-app="app">
<div ng-controller="main">
<form id="form">
<input type="text" />
<input type="text" />
</form>
<button ng-click="clear()">clear</button>
</div>
</div>
JS
angular.module("app", [])
.controller("main", function ($scope) {
$scope.clear = function () {
var inputs = angular.element(document.querySelector('#form')).children();
angular.forEach(inputs, function (value) {
value.value="";
});
};
})
Hope it helps.
Edit
If you give all your inputs that must be cleared a shared class you can select them with the querySelector and erase the fields.
Refer to this page: http://blog.hugeaim.com/2013/04/07/clearing-a-form-with-angularjs/
$setPristine will only clear the variables not the form. To clear the form set their values to blank strings
<script type="text/javascript">
function CommentController($scope) {
var defaultForm = {
author : "",
email : "",
comment: ""
};
$scope.postComments = function(comment){
//make the record pristine
$scope.commentForm.$setPristine();
$scope.comment = defaultForm;
};
}
</script>
Clear topRiskDTO
Looking at your example, seems that clearing topRiskDTO will give you this result.
for instance:
$scope.submit = function(){
// ...
// The submit logic
// When done, Clear topRiskDTO object
for (var key in $scope.topRiskDTO)
{
delete $scope.topRiskDTO[key];
}
};
You have to manually reset the data. See this website for more info.
You also have to call
$form.$setPristine()
To clear all the css classes.
form html
<form action="" method="post" name="add_new_report" id="add_new_report" enctype="multipart/form-data" onsubmit="return AddNewReport(this)">
<div class="field">
<div class="field_180">Cheque</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cheque" id="cheque" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_180">Cash</div>
<div class="field_30">:</div>
<div class="field_220">
<input type="text" name="cash" id="cash" onChange="updatesum()" />
</div>
<div class="clear"></div>
</div>
<div class="field">
<div class="field_210"> </div>
<div class="field_222">
<input type="submit" id="Submit" name="Submit" value="Submit" />
</div>
<div class="clear"></div>
</div>
</form>
in this form user should enter either cheque or cash Field how is it possible ? i don't want to be both are mandatory.
If you absolutely do not care about IE <9 you could use something like the following. (otherwise replace the code not working in IE, with some that does)
function oneShouldHaveData(ids) {
var elements = [];
//convert ids to elements (map no IE<9)
elements = ids.map(function (id) {
return document.querySelector('#' + id);
});
//returns true if any element matches expression (some no IE <9)
return elements.some(function (element) {
//could be validation for anything (greater 0 etc.)
return !!element.value;
});
}
//just submit setup :)
document.querySelector('#add_new_report').addEventListener('submit', function () {
console.log(oneShouldHaveData(['cheque', 'cash']));
});
http://jsfiddle.net/LXprX/1/
Simply add this function to your header:
<script>
function validateForm()
{
var x=document.forms["add_new_report"]["cheque"].value;
var y=document.forms["add_new_report"]["cash"].value;
if ((x==null || x=="") && (y==null || y==""))
{
alert("At least one entry should be filled");
return false;
}
else
return true
}
</script>
and change the following field:
onsubmit="if(validateForm()) return AddNewReport(this)"
You can also include AddNewReport in validateForm function and only return validate(this) function.