How do I make multiple alerts or validation in 1 form?
There is an PHP array option for birthday (date, month, year in array), array choice for job, radio button for gender, checkboxs for passion (can select more than 1 but not empty) and upload file in one form.
Can it be done with a single script?
How to make exclusive alert message to each value, and focus on empty or unselected value?
My form:
<form action="" method="post">
<table width="589" border="1" align="center">
<tr>
<td colspan="3">INPUT DATA</td>
</tr>
<tr style="text-align: left">
<td width="128">NAME</td>
<td width="3">:</td>
<td width="394"><input type="text" name="name" id="name"></td>
</tr>
<tr style="text-align: left">
<td>BIRTHDAY</td>
<td>:</td>
<td><?php
echo "<select name='date' id='date'>";
echo "<option selected='selected'>DATE</option>";
for($a=1; $a<=31; $a+=1)
{
echo"<option value=$a> $a </option>";
}
echo "</select>";
echo "<select name='month' id='month'>";
echo "<option selected='selected'>MONTH</option>";
$month=array(1=>"Januari","Februari","Maret","April","Mei","Juni","July","Agustus","September","Oktober","November","Desember");
for($months=1; $months<=12; $months++)
echo "<option value='$months'>$month[$months]</option>";
echo "</select>";
$now=date('Y');
echo "<select id='year' name='year'>";
echo "<option selected='selected'>YEAR</option>";
for ($a=1980;$a<=$now;$a++)
{
echo "<option value='$a'>$a</option>";
}
echo "</select>";
?>
</td>
</tr>
<tr style="text-align: left">
<td>MAJOR</td>
<td>:</td>
<td> <select name="major" id="major">
echo "<option selected>--SELECT MAJOR--</option>";
<?php
$major=array("INFORMATION SYSTEM"=>"IS","COMPUTER ENGINERING"=>"CE");
foreach($major as $j=>$value)
{echo"<option value='".$value."'>".$j."</option>";
}
?>
</select></td>
</tr>
<tr style="text-align: left">
<td>JOB</td>
<td>:</td>
<td><select name="job" id="job">
echo "<option selected>--SELECT JOB--</option>";
<?php
$choise = array('Actuarial analyst','Business analyst','IT consultant','Network engineer');
for ($job=0;$job<=3;$job++)
{
echo "<option value='".$choise[$job]."'>
".$choise[$job]."</option>";
}
?>
</select></td>
</tr>
<tr style="text-align: left">
<td>SEX</td>
<td>:</td>
<td><input type="radio" name="sex" id="sex" value="MALE">
<label for="radio">MALE
<input type="radio" name="sex" id="sex2" value="FEMALE">
FEMALE</label></td>
</tr>
<tr style="text-align: left">
<td>PASSION</td>
<td>:</td>
<td><input type="checkbox" name="pass[]" value="WRITING">Writing
<input type="checkbox" name="pass[]" value="NETWORKING">Networking
<input type="checkbox" name="pass[]" value="PROGRAMMING">Programming
<input type="checkbox" name="pass[]" value="ENGINERING">Enginering
<input type="checkbox" name="pass[]" value="ETC">Etc</td>
</tr>
<tr style="text-align: left">
<td>FOTO</td>
<td>:</td>
<td><input type="file" name="photo" id="photo"></td>
</tr>
<tr>
<td colspan="3"><input type="submit" name="button" id="submit" value="SAVE"></td>
</tr>
</table>
<label for="name"></label>
</form>
Yo can learn more on validating forms in the following link: Form validation
You need to add a validator script to your form. this is a simple form, it is not working in snippet but you can see it working in this codepen
you just need to add required at the end of required fields
+function ($) {
'use strict';
// VALIDATOR CLASS DEFINITION
// ==========================
var Validator = function (element, options) {
this.$element = $(element)
this.options = options
options.errors = $.extend({}, Validator.DEFAULTS.errors, options.errors)
for (var custom in options.custom) {
if (!options.errors[custom]) throw new Error('Missing default error message for custom validator: ' + custom)
}
$.extend(Validator.VALIDATORS, options.custom)
this.$element.attr('novalidate', true) // disable automatic native validation
this.toggleSubmit()
this.$element.on('input.bs.validator change.bs.validator focusout.bs.validator', $.proxy(this.validateInput, this))
this.$element.on('submit.bs.validator', $.proxy(this.onSubmit, this))
this.$element.find('[data-match]').each(function () {
var $this = $(this)
var target = $this.data('match')
$(target).on('input.bs.validator', function (e) {
$this.val() && $this.trigger('input.bs.validator')
})
})
}
Validator.INPUT_SELECTOR = ':input:not([type="submit"], button):enabled:visible'
Validator.DEFAULTS = {
delay: 500,
html: false,
disable: true,
custom: {},
errors: {
match: 'Does not match',
minlength: 'Not long enough'
},
feedback: {
success: 'glyphicon-ok',
error: 'glyphicon-remove'
}
}
Validator.VALIDATORS = {
'native': function ($el) {
var el = $el[0]
return el.checkValidity ? el.checkValidity() : true
},
'match': function ($el) {
var target = $el.data('match')
return !$el.val() || $el.val() === $(target).val()
},
'minlength': function ($el) {
var minlength = $el.data('minlength')
return !$el.val() || $el.val().length >= minlength
}
}
Validator.prototype.validateInput = function (e) {
var $el = $(e.target)
var prevErrors = $el.data('bs.validator.errors')
var errors
if ($el.is('[type="radio"]')) $el = this.$element.find('input[name="' + $el.attr('name') + '"]')
this.$element.trigger(e = $.Event('validate.bs.validator', {relatedTarget: $el[0]}))
if (e.isDefaultPrevented()) return
var self = this
this.runValidators($el).done(function (errors) {
$el.data('bs.validator.errors', errors)
errors.length ? self.showErrors($el) : self.clearErrors($el)
if (!prevErrors || errors.toString() !== prevErrors.toString()) {
e = errors.length
? $.Event('invalid.bs.validator', {relatedTarget: $el[0], detail: errors})
: $.Event('valid.bs.validator', {relatedTarget: $el[0], detail: prevErrors})
self.$element.trigger(e)
}
self.toggleSubmit()
self.$element.trigger($.Event('validated.bs.validator', {relatedTarget: $el[0]}))
})
}
Validator.prototype.runValidators = function ($el) {
var errors = []
var deferred = $.Deferred()
var options = this.options
$el.data('bs.validator.deferred') && $el.data('bs.validator.deferred').reject()
$el.data('bs.validator.deferred', deferred)
function getErrorMessage(key) {
return $el.data(key + '-error')
|| $el.data('error')
|| key == 'native' && $el[0].validationMessage
|| options.errors[key]
}
$.each(Validator.VALIDATORS, $.proxy(function (key, validator) {
if (($el.data(key) || key == 'native') && !validator.call(this, $el)) {
var error = getErrorMessage(key)
!~errors.indexOf(error) && errors.push(error)
}
}, this))
if (!errors.length && $el.val() && $el.data('remote')) {
this.defer($el, function () {
var data = {}
data[$el.attr('name')] = $el.val()
$.get($el.data('remote'), data)
.fail(function (jqXHR, textStatus, error) { errors.push(getErrorMessage('remote') || error) })
.always(function () { deferred.resolve(errors)})
})
} else deferred.resolve(errors)
return deferred.promise()
}
Validator.prototype.validate = function () {
var delay = this.options.delay
this.options.delay = 0
this.$element.find(Validator.INPUT_SELECTOR).trigger('input.bs.validator')
this.options.delay = delay
return this
}
Validator.prototype.showErrors = function ($el) {
var method = this.options.html ? 'html' : 'text'
this.defer($el, function () {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
var errors = $el.data('bs.validator.errors')
if (!errors.length) return
errors = $('<ul/>')
.addClass('list-unstyled')
.append($.map(errors, function (error) { return $('<li/>')[method](error) }))
$block.data('bs.validator.originalContent') === undefined && $block.data('bs.validator.originalContent', $block.html())
$block.empty().append(errors)
$group.addClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.success)
&& $feedback.addClass(this.options.feedback.error)
&& $group.removeClass('has-success')
})
}
Validator.prototype.clearErrors = function ($el) {
var $group = $el.closest('.form-group')
var $block = $group.find('.help-block.with-errors')
var $feedback = $group.find('.form-control-feedback')
$block.html($block.data('bs.validator.originalContent'))
$group.removeClass('has-error')
$feedback.length
&& $feedback.removeClass(this.options.feedback.error)
&& $feedback.addClass(this.options.feedback.success)
&& $group.addClass('has-success')
}
Validator.prototype.hasErrors = function () {
function fieldErrors() {
return !!($(this).data('bs.validator.errors') || []).length
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter(fieldErrors).length
}
Validator.prototype.isIncomplete = function () {
function fieldIncomplete() {
return this.type === 'checkbox' ? !this.checked :
this.type === 'radio' ? !$('[name="' + this.name + '"]:checked').length :
$.trim(this.value) === ''
}
return !!this.$element.find(Validator.INPUT_SELECTOR).filter('[required]').filter(fieldIncomplete).length
}
Validator.prototype.onSubmit = function (e) {
this.validate()
if (this.isIncomplete() || this.hasErrors()) e.preventDefault()
}
Validator.prototype.toggleSubmit = function () {
if(!this.options.disable) return
var $btn = $('button[type="submit"], input[type="submit"]')
.filter('[form="' + this.$element.attr('id') + '"]')
.add(this.$element.find('input[type="submit"], button[type="submit"]'))
$btn.toggleClass('disabled', this.isIncomplete() || this.hasErrors())
}
Validator.prototype.defer = function ($el, callback) {
callback = $.proxy(callback, this)
if (!this.options.delay) return callback()
window.clearTimeout($el.data('bs.validator.timeout'))
$el.data('bs.validator.timeout', window.setTimeout(callback, this.options.delay))
}
Validator.prototype.destroy = function () {
this.$element
.removeAttr('novalidate')
.removeData('bs.validator')
.off('.bs.validator')
this.$element.find(Validator.INPUT_SELECTOR)
.off('.bs.validator')
.removeData(['bs.validator.errors', 'bs.validator.deferred'])
.each(function () {
var $this = $(this)
var timeout = $this.data('bs.validator.timeout')
window.clearTimeout(timeout) && $this.removeData('bs.validator.timeout')
})
this.$element.find('.help-block.with-errors').each(function () {
var $this = $(this)
var originalContent = $this.data('bs.validator.originalContent')
$this
.removeData('bs.validator.originalContent')
.html(originalContent)
})
this.$element.find('input[type="submit"], button[type="submit"]').removeClass('disabled')
this.$element.find('.has-error').removeClass('has-error')
return this
}
// VALIDATOR PLUGIN DEFINITION
// ===========================
function Plugin(option) {
return this.each(function () {
var $this = $(this)
var options = $.extend({}, Validator.DEFAULTS, $this.data(), typeof option == 'object' && option)
var data = $this.data('bs.validator')
if (!data && option == 'destroy') return
if (!data) $this.data('bs.validator', (data = new Validator(this, options)))
if (typeof option == 'string') data[option]()
})
}
var old = $.fn.validator
$.fn.validator = Plugin
$.fn.validator.Constructor = Validator
// VALIDATOR NO CONFLICT
// =====================
$.fn.validator.noConflict = function () {
$.fn.validator = old
return this
}
// VALIDATOR DATA-API
// ==================
$(window).on('load', function () {
$('form[data-toggle="validator"]').each(function () {
var $form = $(this)
Plugin.call($form, $form.data())
})
})
}(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form data-toggle="validator" action="contact_script" method="post" role="form">
<div class="form-group">
<input name="name" type="text" class="form-control input-lg" placeholder="Your Name" required>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control input-lg" placeholder="E-mail" required>
</div>
<div class="form-group">
<input name="phone" type="text" class="form-control input-lg" placeholder="Contact No." required>
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control input-lg" placeholder="Subject" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control input-lg" rows="5" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn wow bounceInRight" data-wow-delay="0.8s">Send</button>
</form>
Related
I already used this code to display the selected value in the dropdown.But now I have a few dropdown in the list I want to display their selected value in the editing form.Please see the code and guide me.but this code does not work for the list, please see the image.Thank you
#for (var i = 0; i < Model.Count(); i++)
{
<tr>
<td>#Model.ToList()[i].TaminKoonandeName</td>
<td>
<input type="hidden" class="hf_selected_val" value="#Model.ToList()[i].NoaeFactor" />
<select class="mt-1 form-control" name="[#i].NoaeFactor" style="font-size: 12px; width: 130px" required autocomplete="off">
<option value="" default="" selected="">انتخاب کنید</option>
<option value="1">خرید</option>
<option value="2">برگشت از خرید</option>
</select>
</td>
</tr>
}
<script>
$(function () {
$("select[name='NoaeFactor']").each(function () {
var selectedVal = $(this).prev("input[type='hidden']").val();
if (selectedVal != "") {
$(this).val(selectedVal);
}
})
})
</script>
I tried as below:
#{
var sel1 = new List<SelectListItem>() { new SelectListItem() { Text = "A1", Value = "A1" }, new SelectListItem() { Text = "A2", Value = "A2" } };
var sel2 = new List<SelectListItem>() { new SelectListItem() { Text = "B1", Value = "B1" }, new SelectListItem() { Text = "B2", Value = "B2" } };
var sel3 = new List<SelectListItem>() { new SelectListItem() { Text = "C1", Value = "C1" }, new SelectListItem() { Text = "C2", Value = "C2" } };
}
<table id="table">
<tr>
<td>
<input id="input1" />
<select asp-items="sel1"onchange="Somefunc()"></select>
</td>
</tr>
<tr>
<td>
<input id="input2" />
<select asp-items="sel2"onchange="Somefunc()"></select>
</td>
</tr>
<tr>
<td>
<input id="input3" />
<select asp-items="sel3"onchange="Somefunc()"></select>
</td>
</tr>
</table>
<script>
window.onload = function () { Somefunc() }
function Somefunc() {
$('#table tr').each(function () {
$(this).children('td').each(function () {
var selectvalue = $(this).children('select').val().toString()
$(this).children('input').val(selectvalue)
});
});
}
</script>
Result:
Update:
<script>
window.onload = function () { Somefunc() }
function Somefunc() {
$('select').each(function () {
var selectvalue = $(this).prev('input').val().toString()
console.log(selectvalue)
if (selectvalue != null) {
$(this).children("option").each(function () {
if ($(this).text() == selectvalue) {
$(this).attr("selected", "selected")
$(this).val(selectvalue)
}
})
}
})
}
</script>
Result:
I am developing in my final year school project. Now I faced a problem. Some of the onsubmit function in my forms are not functioning well.
The problem is:
I am validating the details filled in in the form. But although the innerHTML already pointed out the wrong by using getElementById, the form still can be submitted. How to stop the form from submitting?
The function does not return any true or false value.
I've already checked through the code. But I can't find the mistakes.
I tried to change the function validate() to window.validate = function(), it does not work well either.
I tried to change the validate function to only return false. The form is still submitting.
I tried event preventDefault but the outcomes become I cannot submit the form.
Javascript part
function check_location() {
var user_address = document.getElementById("location");
var user_address_mess = document.getElementById("addressvalidate");
var checkaddress;
if (user_address.value == "") {
//.....
return false;
} else if (user_address.value.length <= 10) {
//.....
return false;
} else {
//....
return true;
}
}
function check_stime() {
var starttime = document.getElementById("starttime");
var mess_starttime = document.getElementById("mess_starttime");
var check1;
if (starttime != null) {
if (starttime.value == "") {
//...
return false;
}
else if (starttime.value < "08:00" && starttime > "19:00") {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_date() {
today = new Date();
today.setDate(today.getDate() + 14);
var eventdate = document.getElementById("date").value;
eventdate1 = new Date(eventdate);
var mess_date = document.getElementById("mess_date");
var check2;
if (document.getElementById("checkdate") != null) {
var checkdate = document.getElementById("checkdate").innerHTML;
}
if (eventdate != null) {
if (eventdate.value == "") {
//...
return false;
}
else if (eventdate1 <= today) {
//...
return false;
}
else {
//...
return true;
}
}
}
function check_etime() {
var starttime = document.getElementById("starttime");
var endtime = document.getElementById("endtime");
var mess_endtime = document.getElementById("mess_endtime");
var eventdate = document.getElementById("eventdate");
var check3;
if (endtime != null) {
if (endtime.value == "") {
// ...
return false;
}
else if (endtime.value == starttime.value || endtime.value <= starttime.value) {
// ...
return false;
}
else if (endtime.value <= starttime.value && eventdate.value <= fulldate) {
// ...
return false;
}
else if (endtime.value < "09:00" && endtime.value > "22.00pm") {
// ...
return false;
}
else {
//...
return true;
}
}
}
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
return true;
}
}
HTML Part
<div class="g-text-center--xs g-margin-b-40--xs">
<h2 class="g-font-size-30--xs g-color--black">Booking Form</h2>
</div>
<br>
<form autocomplete="off" name="form_submit" onsubmit=" return validate();" method="post" action="">
<div class="g-margin-b-30--xs">
<p><b>Package Name :</b>
<input type="text" name="pname" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="<?php echo $pack1['package_name']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<p><b>Package Price :</b>
<input type="text" name="pprice" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" value="RM <?php echo $pack1['package_price']?>" style="width:200px; font-weight:bold; color:black;" disabled>
</p>
</div>
<div class="g-margin-b-30--xs">
<b>Event Date :</b>
<input onfocusout="check_date()" name="date" id="date" type="date" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:400px; color:black;">
<span id="mess_date" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>Start Time :</b>
<input onfocusout="check_stime()" name="starttime" id="starttime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_starttime" style="color:red;font-weight:normal;"></span>
</div>
<div class="g-margin-b-30--xs">
<b>End Time :</b>
<input onfocusout="check_etime()" name="endtime" id="endtime" type="time" class="form-control s-form-v3__input g-bg-color--white-opacity-lightest" style="width:500px;" />
<span id="mess_endtime" style="color:red;font-weight:normal;"></span>
</div>
<b>Event Location : </b>
<br>
<textarea class="form-control s-form-v2__input" name="location" id="location" style=" width:500px; font-weight:bold; text-align:left;" onfocusout="check_location()"></textarea>
<span style="color:red;font-weight:normal;" id="addressvalidate"></span>
<div class="g-text-center--xs">
<br>
<button style="margin-bottom:50px;" type="submit" id="submit" name="addtocart" class="btn btn-primary"><span class="glyphicon glyphicon-floppy-disk"></span> Submit</button>
<div class="clearfix"> </div>
</div>
</form>
I want to prevent the form from submitting when there is something wrong.
You can easily fix this by changing your code to this.
<form id="myForm" onsubmit="event.preventDefault(); validate();">
and change validate() javascript function to this.
function validate() {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
return false;
} else {
document.getElementById("myForm").submit();
}
}
On click of the submit button add something like below
<button onclick="return validate()" style="margin-bottom:50px;" type="submit" id="submit" name = "addtocart" class = "btn btn-primary"><span class = "glyphicon glyphicon-floppy-disk"></span> Submit</button>
In the validate() function ,you if you return true it will submit,if you return false, it will not submit form,there you can show the error message
Remove everything from the form tag all the submit lines and simply give it a unique id and same goes to the button tag too something like this
<form id ="my_form" action="/action_page.php">
<button id="u_id">submit</button>
</form>
Then in java script part
var form = document.getElementById("my_form");
document.getElementById("u_id").addEventListener("click", function () {
checkstime = check_stime();
checketime = check_etime();
checkdate = check_date();
checklocation = check_location();
if (checklocation == false || checkstime == false || checketime == false || checkdate == false) {
//show error msg
} else {
form .submit();
}
});
I am reading a chapter from PHP Ajax Cookbook. Here is the code:
HTML:
<form class='simpleValidation'>
<div class='fieldRow'>
<label for='title'>Title *</label>
<input type='text' id='title' name='title' class='required'>
</div>
<div class='fieldRow'>
<label for='url'>URL</label>
<input type='text' id='url' name='url' value='http://'>
</div>
<div class='fieldRow'>
<label for='labels'>Labels</label>
<input type='text' id='labels' name='labels'>
</div>
<div class='fieldRow'>
<label for='textarea'>Text *</label>
<textarea id='textarea' class='required'></textarea>
</div>
<div class='fieldRow'>
<input type='submit' id='formSubmitter' value='Submit'>
</div>
</form>
jQuery:
$(document).ready(function() {
var timerId = 0;
$('.required').keyup(function() {
clearTimeout(timerId);
timerId = setTimeout(function() {
ajaxValidation($(this));
}, 200);
});
});
var ajaxValidation = function (object) {
var $this = $(object);
var param = $this.attr('name');
var value = $this.val();
$.get(
'inputValidation.php',
{'param' : param, 'value' : value },
function (data) {
if (data.status == 'OK') {
validateRequiredInputs();
} else {
$this.addClass('failed');
}
},
'json'
);
var validateRequiredInputs = function() {
var numberOfMissingInputs = 0;
$('.required').each(function(i) {
var $item = $(this);
var itemValue = $item.val();
if (itemValue.length) {
$item.removeClass('failed');
} else {
$item.addClass('failed');
numberOfMissingInputs++;
}
});
var $submitButton = $('#formSubmitter');
if (numberOfMissingInputs > 0) {
$submitButton.prop('disabled', true)
} else {
$submitButton.prop('disabled', false)
}
}
}
PHP (inputValidation.php):
<?php
$result = array();
if (isset($_GET['param'])) {
$result['status'] = 'OK';
$result['message'] = 'Input is valid!';
} else {
$result['status'] = 'ERROR';
$result['message'] = 'Input IS NOT valid';
}
echo json_encode($result)
?>
When I start typing in the Title * field I get the following error from the console: Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
Note: I am using jQuery 2.2.1
So far I have checked the code for mis-spelling but cannot find any.
The this bit in ajaxValidation($(this)) isn't what you think it is: it's actually window, since it's being called by setTimeout().
One solution is to assign $(this) to a variable outside the function, like so:
$('.required').keyup(function() {
clearTimeout(timerId);
var $this = $(this);
timerId = setTimeout(function() {
ajaxValidation($this);
}, 200);
});
If I give semicolon as input means I have to create a textbox in jQuery. I tried this code and it flows correctly but it didn't show me the result.
$(document).ready(function (){
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 59)
{
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
alert("friends");
addbox();
}
}
});
});
addbox code is here
function addbox() {
var table = $(this).closest('table');
if (table.find('input:text').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
My ASp.Net Markup is
<asp:TextBox ID="hellotxt" runat="server" placeholder="hi;ji;ki;li;"> </asp:TextBox>
<table border="0" cellspacing="2">
<tr>
<td>
<input type="button" id="add" value="Add" />
<input type="button" id="del" value="Del" />
</td>
</tr>
you will get answer from this code..please you all guys check it out
$(document).ready(function (){
//page load
$("#hellotxt").on('keypress', function (event) {
console.log(event.which)
if (event.which == 59 || event.which == 186) {
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox.call(this, valueSortArray);
}
}
});
function addbox(valueSortArray) {
var table = $(this).next('table').find("tbody");
table.find(".dyn").remove()
$.each(valueSortArray, function (i, v) {
console.log(i,v)
if (v)
table.append('<tr class="dyn"><td><input type="text" value="' + v + '" /></td></tr> ');
})
check below code keycode for ';' is 186 . check working example on fiddle
$("#hellotxt").on('keyup', function (event){
if (event.keyCode == 186)
{
var OBJ = $(this);
var txt = $("#hellotxt").val();
var valueArray = txt.split(';');
var valueSortArray = valueArray.sort();
for (var i = 0; i < valueSortArray.length - 1; i++) {
addbox(OBJ);
}
}
});
pass $(this)(hellotxt object) as argument in function
function addbox( OBJ ) {
var table = OBJ.next('table');
if (table.find('input').length >= 0) {
table.append('<tr> <input type="text" id="current Name" value="" /></td> <td><input type="text" id="current Name" value="" /> </td></tr>');
}
}
i made my form in table mode
like this:
<form name="register" method="post" action="#" onSubmit="return validasi()">
<table width="507" border="0">
<h1 class="title">Form Perubahan Password</h1>
<tr>
<td width="190" ><span id="usernameerror" class="style20">Masukkan Username </span></td>
<td width="319"><input name="username" type="text"></td>
</tr>
<tr>
<td><span id="passworderror" class="style20">Masukkan Password Lama</span></td>
<td><input name="pass" type="password"></td>
</tr>
<tr>
<td><span id="password1error" class="style20">Masukkan Password Baru</span></td>
<td><input name="pass1" type="password"></td>
</tr>
<tr>
<td><span id="password2error" class="style20">Ulangi Masukkan Password Baru</span></td>
<td><input name="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>
and this my validation code with javascript. check it out..
<script language="javascript">
function checkName(register)
{
var eobj = document.getElementById('usernameerror');
var susername = register.username.value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
eobj.innerHTML = '';
if (susername == '') {
error = 'Error: Username tidak boleh kosong';
register.username.focus();
}
else if (!oRE.test(susername))
{
error="Salah format";
}
if (error)
{
register.username.focus();
eobj.innerHTML = error;
return false;
}
return true;
}
function validatePwd(register) /* old password verification */
{
var eobj = document.getElementById('passworderror');
var invalid = ' ';
var pw = register.pass.value;
var error = false;
eobj.innerHTML = '';
if (pw.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass.focus();
eobj.innerHTML = error;
return false
}
return true;
}
function validatePwd1(register) /* password & retype-password verification */
{
var eobj1 = document.getElementById('password1error');
var eobj2 = document.getElementById('password2error');
var invalid = ' ';
var pw1 = register.pass1.value;
var pw2 = register.pass2.value;
var error = false;
eobj1.innerHTML = '';
eobj2.innerHTML = '';
if (pw1.length < 1)
{
error = 'Masukkan password anda';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'Anda harus mengisi password';
}
if (error)
{
register.pass1.focus();
eobj1.innerHTML = error;
return false
}
if (pw1 != pw2)
{
eobj2.innerHTML = ' password tidak sama, coba masukkan kembali password anda';
return false;
}
return true;
}
function validasi()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
When i use this validation in usually form its work But in table mode that's validation code doesn't work..help me to solve this problem...tq
view demo
http://jsfiddle.net/andricoga/u9eZz/
You have declared onSubmit="return validasi()" in form , but where you defined function for that. for validation working you need to define function for that.
function validasi(){
// validation code goes here
}
In your validatePwd() function replace
eobj1.innerHTML = error;
with
eobj.innerHTML = error;
you have not defined this eobj1 object and hence it is causing a run time javascript error.
I changed the code to display the error beside the field, try this out
Javascript
<script language="javascript">
function checkName()
{
var obj = document.getElementById('usernameerror');
var susername = document.getElementById('username').value;
var oRE = /^[a-z0-9]+[_.-]?[a-z0-9]+$/i;
var error = false;
obj.innerHTML = '';
if (susername == '') {
error = 'Username can not be empty';
}
else if (!oRE.test(susername))
{
error = 'One format';
}
if (error)
{
document.getElementById('username').focus();
obj.innerHTML = error;
return false;
}
return true;
}
function validatePwd() /* password & retype-password verification */
{
var obj = document.getElementById('pwderror');
var invalid = ' ';
var pw = document.getElementById('pass').value;
var error = false;
obj.innerHTML = '';
if (pw.length < 1)
{
error = 'Enter your old password';
}
else if (pw.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass').focus();
obj.innerHTML = error;
return false
}
return true;
}
function validatePwd1() /* password & retype-password verification */
{
var obj = document.getElementById('pwd1error');
var invalid = ' ';
var pw1 = document.getElementById('pass1').value;
var pw2 = document.getElementById('pass2').value;
var error = false;
obj.innerHTML = '';
if (pw1.length < 1)
{
error = 'Enter your new password';
}
else if (pw1.indexOf(invalid) > -1)
{
error = 'You need a password';
}
if (error)
{
document.getElementById('pass1').focus();
obj.innerHTML = error;
return false
}
if (pw1 != pw2)
{
obj.innerHTML = 'passwords are not the same, try to re-enter your password';
return false;
}
return true;
}
function validate()
{
var form = document.forms['register'];
var ary = [checkName, validatePwd, validatePwd1];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++)
{
if (!ary[z0](form))
{
rtn = false;
}
}
return rtn;
}
</script>
Form
<form name="register" method="post" action="#" onSubmit="return validate()">
<table border="0">
<tr>
<td colspan="2">
<h1 class="title">Password Change Form</h1>
</td>
</tr>
<tr>
<td><span class="style20">Username </span></td>
<td><input name="username" id="username" type="text"></td>
<td><span id="usernameerror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Old Password</span></td>
<td><input name="pass" id="pass" type="password"></td>
<td><span id="pwderror" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">New Password</span></td>
<td><input name="pass1" id="pass1" type="password"></td>
<td><span id="pwd1error" class="style20"> </span></td>
</tr>
<tr>
<td><span class="style20">Repeat New Password</span></td>
<td><input name="pass2" id="pass2" type="password"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="Submit">
<input type="reset" name="reset" value="Reset"></td>
</tr>
</table>
</form>