scroll the div to error position in jquery - scroll

Need to focus the first error input field,then second if first is filled and so on......,but the code which i have written focus the last field first, may be i know what is the reason behind it but not able to find out the solution.....So many a thanks if u guys help me as i m new to programming.
function contactvalidate()
{
var error=0;
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var email = $('#email').val();
if($.trim(firstname) =="")
{
$("#firstname + p").remove();
error=error+1;
$("#firstname").after("<p>Enter first name</p>");
$("#firstname").focus();
}
else
{
$("#firstname + p").remove();
}
if($.trim(lastname) =="")
{
$("#lastname + p").remove();
error=error+1;
$("#lastname").after("<p>Enter last name</p>");
$("#lastname").focus();
}
else
{
$("#lastname + p").remove();
}
if(email =="")
{
$("#email + p").remove();
error=error+1;
$("#email").after("<p>Enter email </p>");
$("#email").focus();
}
else if (IsEmail(email)==false)
{
$("#email + p").remove();
error=error+1;
$("#email").after("<p>Enter Valid E-mail</p>");
$("#email").focus();
}
else
{
$("#email + p").remove();
}
if (error==0)
{
return true;
}
else{
return false;
}
}
Here is the Html
<form action="register.php" method="post" enctype="multipart/form-data" >
<div class="field_area">
<label>First Name<span>*</span>:</label><input type="text" value="<?php echo $firstname ?> " name="firstname" id="firstname" ></input>
</div>
<div class="field_area">
<label>Last Name<span>*</span>:</label><input type="text" value=" <?php echo $lastname ?>" name="lastname" id="lastname" ></input>
</div>
<div class="field_area">
<label>Email<span>*</span>:</label><input type="text" name="email" value="<?php echo $email ?>" id="email"></input><?php echo "<p>" . "$emailexit"."</p>"; ?>
</div>
<div class="field_area">
<input type="submit" value="Submit" name="submit" onclick=" return contactvalidate();"></input>
</div>
</form>

Try this but ur validation code is poor...
U need to stop the further execution of code after every .focus() hence return false else the execution continues...
function contactvalidate()
{
var error=0;
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
var email = $('#email').val();
if($.trim(firstname) =="")
{
$("#firstname + p").remove();
error=error+1;
$("#firstname").after("<p>Enter first name</p>");
$("#firstname").focus();
return false;
}
else
{
$("#firstname + p").remove();
}
if($.trim(lastname) =="")
{
$("#lastname + p").remove();
error=error+1;
$("#lastname").after("<p>Enter last name</p>");
$("#lastname").focus();
return false;
}
else
{
$("#lastname + p").remove();
}
if(email =="")
{
$("#email + p").remove();
error=error+1;
$("#email").after("<p>Enter email </p>");
$("#email").focus();
return false;
}
else if (IsEmail(email)==false)
{
$("#email + p").remove();
error=error+1;
$("#email").after("<p>Enter Valid E-mail</p>");
$("#email").focus();
return false;
}
else
{
$("#email + p").remove();
}
if (error==0)
{
return true;
}
else{
return false;
}
}

Related

Fetch corresponding value of a drop downlist

I want to fetch the corresponding value of my dropdown the image below shows the form and the database. the table was inside the javascript and Iam having a dificult time in figuring out this problem. please help me how to solve this problem... Thank you very much in advance...
Database
forms entry
My Controller
function getFeetypeEndDate() {
$feetype_id = $this->input->get('feety_id[]');
$data = $this->feegroup_model->getFeetypeByEndDate($feetype_id);
echo json_encode($data);
}
My Model
public function get($id = null) {
$this->db->select()->from('feetype');
$this->db->where('is_system', 0);
if ($id != null) {
$this->db->where('id', $id);
} else {
$this->db->order_by('id');
}
$query = $this->db->get();
if ($id != null) {
return $query->row_array();
} else {
return $query->result_array();
}
}
My Javascript in the View Section
<script>
$(document).ready(function (){
$("body").on('click', '.btn-add-more', function (e) {
e.preventDefault();
var amount = $("#amount").val();
var penalty = $("#penalty").val();
var $sr = ($(".jdr1").length + 1);
var rowid = Math.random();
var $html = '<tr class="jdr1" id="' + rowid + '">' +
'<td><span class="btn btn-sm btn-default">' + $sr + '</span><input type="hidden" name="count[]" value="'+Math.floor((Math.random() * 10000) + 1)+'"></td>' +
'<td><select id="feetype_id[]" name="feetype_id[]" class="form-control" >' +
'<?php foreach ($feetypeList as $feetype) { ?>' +
' <option value="<?php echo $feetype['id'] ?>" ' +
'<?php if (set_value('feetype_id[]') == $feetype['id']) { echo "selected =selected"; } ?>><?php echo $feetype['type'] ?></option> <?php $count++; } ?> </select></td>' +
'<td><input type="text" id="startDate" name="startDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->start_date), $this->customlib->dateyyyymmddTodateformat($feetype->start_date)); ?>" placeholder="Start Date" class="form-control input-sm"/></td>' +
'<td><input type="text" id="endDate" name="endDate" value="<?php echo date($this->customlib->getSchoolDateFormat($feetype->end_date), $this->customlib->dateyyyymmddTodateformat($feetype->end_date)); ?>" placeholder="End Date" class="form-control input-sm"/></td>' +
'<td><input type="text" name="amount_td[]" placeholder="Amount" class="form-control input-sm" value="'+amount+'"></td>' +
'<td><input type="text" name="penalty_td" placeholder="Penalty" class="form-control input-sm" value="'+penalty+'"></td>' +
'</tr>';
$("#table-details").append($html);
});
$("body").on('click', '.btn-remove-detail-row', function (e) {
e.preventDefault();
if($("#table-details tr:last-child").attr('id') != 'row1'){
$("#table-details tr:last-child").remove();
}
});
});

Default value of drop-down list with JavaScript and JSON

I have a City field in my form when user select his province/state a drop-down list of cities appear according to selected state. However for the cities list there is no default value like 'Select your city'. I want to add this value.
Below is my field.js :
function getAjaxReqest(action, selectCountry, stateId, normalImput,selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('billing:city').replace('<select id="billing:city" name="billing[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: $('billing:city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestCustomer(action, selectCountry, stateId, normalImput, selectedCity) {
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('city').replace('<select id="city" name="city" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this, selectedCity) +
'</select>');
},
onFailure: $('city').replace(normalImput),
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function getAjaxReqestShip(action, selectCountry, stateId, normalImput,selectedCity) {
if (normalImput != null) {
var resetShip = true;
} else {
var resetShip = false;
}
var request = new Ajax.Request(action,
{
method: 'GET',
onSuccess: function (data) {
$('shipping:city').replace('<select id="shipping:city" name="shipping[city]" class="required-entry">' +
'<option value=""></option>' + convertJsonToHtml(data.responseText, this,selectedCity) +
'</select>');
},
onFailure: function (resetShip) {
if (resetShip) {
$('shipping:city').replace(normalImput)
}
},
parameters: {city_id: stateId, country_id: selectCountry}
}
);
}
function convertJsonToHtml(data, ship, selectedCity) {
var jsonData = data.evalJSON();
if (jsonData.length == 0) {
ship.replace(normalImput);
return;
}
console.log(jsonData);
htmlData = '';
jsonData.each(function (item) {
if (item.cityname == selectedCity) {
htmlData += '<option value="' + item.cityname + '" selected>' + item.cityname + '</option>';
} else {
htmlData += '<option value="' + item.cityname + '">' + item.cityname + '</option>';
}
});
return htmlData;
}
While the following code generates the City field on frontend in the form.
<div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')->getAttributeValidationClass('city') ?>"
id="billing:city"/>
</div>
Any help and tips are appreciated.I am a novice in Javascript and JSON so i am having a hard time playing with it.
EDIT:
I tried this:
div class="input-box">
<input type="text" title="<?php echo $this->__('City') ?>" name="billing[city]"
value="<?php echo $this->escapeHtml($this->getAddress()->getCity()) ?>"
class="input-text <?php echo $this->helper('customer/address')- >getAttributeValidationClass('city') ?>"
id="billing:city"/>
<select name="anything"><option value="undefined" disabled="selected">Select your city</option></select>
</div>
This works but adds the text 'Select your city' below the city field NOT inside it.
use this code as default showing before selecting city (i.e)set value as "undefined" disabled selected.
' +
'Select your city' + convertJsonToHtml(data.responseText, this, selectedCity) +
''

ajaxupload el is undefined

i haved trying to use ajax upload image. here is my code
$(function () {
var btnUpload = $('#post_pd_thumnail');
if ($("#id").val()) var post_id = $("#id").val();
else var post_id = 0;
new AjaxUpload(btnUpload, {
action: site_root_domain + "/product/upload_image/" + post_id,
name: 'file_upload',
onSubmit: function (file, ext) {
if ($('#post_pd_thumnail').val() != '') {
if (!(ext && /^(jpg|png|jpeg|gif)$/.test(ext))) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
return false;
}
}
$('#preview').html('<img style="margin-left:45px;margin-top:45px;" border="0" width="16" height="11" src="' + site_root_domain + '/templates/images/icons/loading_2.gif" />');
},
onComplete: function (file, response) {
if (!response) {
jAlert(lang_error_upload_avatar, lang_alert_notice);
} else {
img_upload = 1;
$('#preview').html(response);
}
return;
}
});
});
And my HTML is:
<div id="preview">{$preview}</div>
<div class="fileupload">
<input type="file" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>
<input type="hidden" name="id" id="id" value="{$data['product']['post_id']}" />
and i got this error when upload image "el is undefined" and the function does not work correctly can anyone help me solve this problem please
Try to change the file element to button like,
<div class="fileupload">
<input type="button" name="post_pd_thumnail" id="post_pd_thumnail" value="" />
</div>
Here is the solution.
* Attaches event to a dom element
*/
function addEvent(el, type, fn){
// 610 BUG
if (el == undefined) return;
if (w.addEventListener){
el.addEventListener(type, fn, false);
} else if (w.attachEvent){
var f = function(){
fn.call(el, w.event);
};
el.attachEvent('on' + type, f)
}
}

what is wrong with my code? I need to validate a radio button

what is wrong with my code? I need to validate a radio button.
it works fine until the last item. after I select Yes or No, I get to submit the form with the last option empty. I cant seem to validate the last option.
also I didnt write this script. I honestly dont understand how it works :/
this is what I have
function valida () {
if (document.example.name.value=="") {
alert ('NAME field is empty!');
return false;
}
else if (document.example.email.value=="") {
alert ('EMAIL field is empty!');
return false;
}
var radios = document.getElementsByName("yesorno");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Select Yes or No!");
return formValid;
var radios = document.getElementsByName("color");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid) alert("Pick a colour!");
return formValid;
else {
return true;
}
}
<form name="example" id="example" action="submit-form.php" method="post" onsubmit="return valida();">
<fieldset>
<label for="name">Name:</label>
<input type="text" name="name" id="name"/>
<label for="email">Email:</label>
<input type="text" name="email" id="email"/>
<label>Yes or No?</label>
YES
<input name="yesorno" type="radio" class="radio" value="yes" />
NO
<input name="yesorno" type="radio" class="radio" value="yes" />
<label>Red, green or yellow?</label>
red
<input name="color" type="radio" class="radio" value="red" />
green
<input name="color" type="radio" class="radio" value="green" />
yellow
<input name="color" type="radio" class="radio" value="yellow" />
<input type="submit" value="submit" />
</fieldset>
</form>
edit:
I found a solution here on stackoverflow. this works for me now:
function valida () {
if (document.example.name.value=="") {
alert ('NAME field is empty!');
return false;
}
else if (document.example.email.value=="") {
alert ('EMAIL field is empty!');
return false;
}
else if ($('input[name=yesorno]:checked').length == 0) {
alert ('Select Yes or No!');
return false;
}
else if ($('input[name=color]:checked').length == 0) {
alert ('Pick a colour!');
return false;
}
else {
return true;
}
}
You're returning the "Yes/No" validation before the rest of the code can be reached. If the return is enclosed in the if statement, the rest of the code will be reached. Try this:
<script language=javascript>
function valida ()
{
if (document.example.name.value=="")
{
alert ('NAME field is empty!');
return false;
}
else if (document.example.email.value=="")
{
alert ('EMAIL field is empty!');
return false;
}
var radios = document.getElementsByName("yesorno");
var formValid = false;
var i = 0;
while (!formValid && i < radios.length)
{
if (radios[i].checked) formValid = true;
i++;
}
if (!formValid)
{
alert("Select Yes or No!");
return formValid;
}
radios = document.getElementsByName("color");
formValid = false;
i = 0;
while (!formValid && i < radios.length)
{
if (radios[i].checked)
{
formValid = true;
}
i++;
}
if (!formValid)
{
alert("Pick a colour!");
return formValid;
}
else
{
return true;
}
}
Name:
Email:
Yes or No?
YES
NO
Red, green or yellow?
red
green
yellow

file upload does not work in IE 8, IE 9

i have the following code to upload a file, which runs without error in mozilla firefox and google chrome but gives error in IE 8. Please provide solution. This is my view-
#using (Html.BeginForm(null, null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<fieldset>
<div class="input_panelleft">
<div class="input_panellabel">
#Html.LabelFor(model => model.DrawingName)
</div>
<div class="input_panelinput">
#Html.EditorFor(model => model.DrawingName)
</div>
<div class="input_panellabel">
Upload Drawing
</div>
<div class="input_panelinput">
<input type="file" name='file' id='file' />
</div>
<div class="center">
<input type="submit" value="Upload" />
</div>
</div>
</fieldset>
}
and following code in controller-
[HttpPost]
public ActionResult Create(DrawingDocumentsModel model, HttpPostedFileBase file)
{
if (ModelState.IsValid)
{
if (file != null)
{
var documentNameParts = file.FileName.Split('.');
var documentExtension = documentNameParts.Last();
var documentNameOnly = String.Join(".", documentNameParts.Take(documentNameParts.Length - 1));
var filename = documentNameOnly + "." + documentExtension;
if (_drawingDocumentService.IsDrawingNameAvailable(filename))
{
var path = Server.MapPath("~/Uploads/");
var Filepath = Path.Combine(path, filename);
file.SaveAs(Filepath);
var drawingDocuments = new DrawingDocuments();
drawingDocuments.ProjectId = 1;
drawingDocuments.ProjectName = "Drawing Tag";
drawingDocuments.FileName = filename;
drawingDocuments.UploadedDate = System.DateTime.Now;
drawingDocuments.UploadedBy = _workContext.CurrentUserId;
if (model.DrawingName == "" || model.DrawingName == null)
{
ModelState.AddModelError("CustomError", "Please Enter Drawing Name");
}
else
{
drawingDocuments.DrawingName = model.DrawingName;
drawingDocuments.Path = ("/Uploads/" + filename);
_drawingDocumentService.InsertDrawingDocument(drawingDocuments);
return RedirectToAction("DrawingDocuments");
}
}
else
{
ModelState.AddModelError("CustomError", "Drawing With Same File Name Already Available");
}
}
else
{
ModelState.AddModelError("CustomError", "Please Select Drawing");
}
}
return View(model);
}

Resources