How do I Auto Capitalize all the value of my dynamic text box. I want on submit for security purposes. I used strtooper in PHP but it has an array problem. And I used auto capitalization using CSS but if the value is already submitted to database it is not working, it's still the same as the value I inputted. Anyone can help me.
main form:
<script type='text/javascript'>
/* attach a submit handler to the form */
$(document).ready(function() {
$('#submitme').on('submit', function(e) {
var mytxt1 = [];
var mytxt2 = [];
$(".car_brand").each(function () {
mytxt1.push($(this).val());
});
$(".car_model").each(function () {
mytxt2.push($(this).val());
});
e.preventDefault();
var perfTimes = $(this).serialize();
$.post("maintenance_function.php", {results: perfTimes, txt1: mytxt1, txt2: mytxt2 }, function (data) {
if (data.errors) {
var alertErrors = "The following errors were found: ";
$.each(data.errors, function(index, error){
alertErrors += "\n" + "\n" + error.message;//Add each error in a new line
});
alert(alertErrors);
}
else {
alert(data.message);
window.location.href = data.redirect;
}
}, "json");
});
});
<script>
var nitem =0;
var ntotal = 0;
$('.btn').click(function() {
nitem++;
$('#wrapper').append('<div id="div' + nitem + '" class="inputwrap">' +
'Car Manufacturer: <input type="text" class="car_brand" id="' + nitem + '" required> ' +
'Car Model: <input type="text" class="car_model" id="' + nitem + '" required>' +
'<br><br></div>');
});
$('.btn2').click(function() {
ntotal = $('#total').val();
$("#div" + nitem).each(function(){
});
$("#div" + nitem ).remove();
nitem--;
$('#total').val(ntotal); });
</script>
Function form:
<?php
include('connect.php');
$mydata = $_POST["results"];
//echo $mydata;
parse_str($mydata);
$inputs = [];
parse_str($mydata, $inputs);
extract($inputs);
$errors = [];
if(!isset($_POST["txt1"])){
$errors[] = array(
'error_code' => 1,
'message' => 'Please add a text box.'
);
}
if(empty($errors)) {
for($i=0;$i<=count($_POST["txt1"])-1;$i++)
{
//if (trim($_POST["txt1"][$i]) != "" && trim($_POST["txt2"][$i]) != "" && trim($_POST["txt3"][$i]) != ""){
mysql_query("INSERT INTO car_maintenance VALUES ('', '". $_POST["txt1"][$i] ."','". $_POST["txt2"][$i] ."')");
//}
}
$response = array(
'message' => 'Successfully Added',
'redirect' => "car_maintenance.php"//add here
);
echo json_encode($response);
}
else {
$response = array(
'errors' => $errors
);
echo json_encode($response);
}
?>
use this on the string you want to capitalize in the php file:
$newstring = ucwords(strtolower($string1));
this will create “title case,” where the first
letter of each word is in uppercase and the rest of the letters are in lowercase, hopw this is what you meant.
if you want all letters capital, use this:
$newstring = strtoupper($string1);
In css
input {text-transform:uppercase;}
In javascript
document.getElementsByTagName('input').value = document.getElementsByTagName('input').value.toUpperCase()
Related
I am trying to make AJAX form validation work in CodeIgniter.
If you have the same title don't add The data from the form always reports as successful, even if the result is negative.
Is there a mistake in my logic?
Save controller:
public function save(){
$options = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$data['options'] = json_encode($options);
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$validate = $this->form_validation->run();
if($validate){
$insert = $this->db->insert('product', $data);
// alert
if($insert){
$alert = array(
"title" => "Success Sir",
"text" => "Content successfully added",
"type" => "success"
);
}else {
$alert = array(
"title" => "Error Sir",
"text" => "Content failed to load content,
"type" => "danger"
);
}
}
JSON, AJAX, jQuery:
function ajax_set_full(type, title, noty, form_id, id) {
// ajax func
ajax_load(base_url + '' + user_type + '/' + module + '/' + type + '/' + id, 'list', 'form');
}
function form_submit(form_id, noty, e) {
var alerta = $('#form'); // alert div for show alert message
var form = $('#' + form_id);
var can = '';
if (!extra) {
var extra = '';
}
form.find('.summernotes').each(function () {
var now = $(this);
now.closest('div').find('.val').val(now.summernote('code'));
});
//var form = $(this);
var formdata = false;
if (window.FormData) {
formdata = new FormData(form[0]);
}
var a = 0;
var take = '';
form.find(".required").each(function () {
var txt = '*' + req;
a++;
if (a == 1) {
take = 'scroll';
}
var here = $(this);
if (here.val() == '') {
if (!here.is('select')) {
here.css({borderColor: 'red'});
if (here.attr('type') == 'number') {
txt = '*' + mbn;
}
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' ' + txt
+ ' </span>'
);
}
} else if (here.is('select')) {
here.closest('div').find('.chosen-single').css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="label label-danger require_alert" >'
+ ' *Required'
+ ' </span>'
);
}
}
var topp = 100;
if (form_id == 'product_add' || form_id == 'product_edit') {
} else {
$('html, body').animate({
scrollTop: $("#scroll").offset().top - topp
}, 500);
}
can = 'no';
}
if (here.attr('type') == 'email') {
if (!isValidEmailAddress(here.val())) {
here.css({borderColor: 'red'});
if (here.closest('div').find('.require_alert').length) {
} else {
here.closest('div').append(''
+ ' <span id="' + take + '" class="require_alert" >'
+ ' *' + mbe
+ ' </span>'
);
}
can = 'no';
}
}
take = '';
});
if (can !== 'no') {
if (form_id !== 'vendor_pay') {
$.ajax({
url: form.attr('action'), // form action url
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formdata ? formdata : form.serialize(), // serialize form data
cache: false,
contentType: false,
processData: false,
beforeSend: function () {
console.log(formdata);
var buttonp = $('.enterer');
buttonp.addClass('disabled');
buttonp.html(working);
},
success: function () {
ajax_load(base_url + '' + user_type + '/' + module + '/' + list_cont_func + '/' + extra, 'list', 'first');
if (form_id == 'vendor_approval') {
noty = enb_ven;
}
iziToast.show({
color: 'dark',
icon: 'fa fa-info',
title: 'Bilgi',
message: 'İşlem Başarılı!',
position: 'topCenter', // bottomRight, bottomLeft, topRight, topLeft, topCenter, bottomCenter
progressBarColor: 'rgb(0, 255, 184)',
/*onOpening: function(){
setTimeout(function(){
window.location.reload(1);
}, 5000);
console.log('Page Refresh!');
},
onClosing: function(){
// console.log('goodbye');
}*/
});
$('.bootbox-close-button').click();
('form_submit_success');
other_forms();
},
error: function (e) {
console.log(e)
}
});
} else {
//form.html('fff');
form.submit();
//alert('ff');
return false;
}
} else {
if (form_id == 'product_add' || form_id == 'product_edit') {
var ih = $('.require_alert').last().closest('.tab-pane').attr('aria-labelledby');
$("[id=" + ih +"]").click();
}
$('body').scrollTo('#scroll');
return false;
}
}
The error message always returns positive.
after run the validation, you need specify the array to be validated
public function save(){
$data = array();
$data['title'] = $this->input->post('title');
$data['description'] = $this->input->post('description');
$data['sale_price'] = $this->input->post('sale_price');
$data['purchase_price'] = $this->input->post('purchase_price');
$data['add_timestamp'] = time();
$this->form_validation->set_rules("title", "Title", "required|trim|is_unique[product.title]");
$this->form_validation->set_rules("description", "Description", "required|trim");
$this->form_validation->set_rules("sale_price", "Price", "required|trim");
$this->form_validation->set_message(
array(
"required" => "<b>{field}</b> is not null.",
'is_unique' => 'A %s content has already been added in thistitle.!'
)
);
$this->form_validation->set_data($data);
$validate = $this->form_validation->run();
You have to call the set_data() method before defining any validation rules.
Ref: https://codeigniter.com/userguide3/libraries/form_validation.html#validating-an-array-other-than-post
I have a bit of a bug, and I can't tell where the error comes from.
I am building a cart system that will insert multiple data to a database from a cart on submit.
I'm using AJAX for this and I'm have errors, please I need help.
Here are my code snippets:
JavaScript Code
function addSale(payment_type, cash_tendered) {
var cust_name = $("#cust_name").val();
var amt_owed = $("#amt_owed").val();
$.confirm({
title: 'Checkout',
content: '' +
'<form action="" class="formName" role="form">' +
'<div class="form-group">' +
'<label>Payment Type</label>' +
'<select id="eType" class="name form-control">' +
'<option value="cash">Cash</option>' +
'<option value="card">Card</option>' +
'</select>' +
'</div>' +
'<div class="form-group">' +
'<label>Cash Tendered</label>' +
'<input type="number" id="eCash" placeholder="Cash Tendered" class="name form-control">' +
'</div>' +
'</form>',
buttons: {
cancel: function () {
//close
},
formSubmit: {
text: 'Checkout',
btnClass: 'btn-success',
action: function () {
payment_type = this.$content.find('#eType').val();
cash_tendered = this.$content.find('#eCash').val();
if (!payment_type || !cash_tendered) {
$.alert('Please fill all fields.');
return false;
}
$.confirm({
title: 'Do you want to continue?',
type: 'orange',
content: 'Click Ok to add sale',
buttons: {
cancel: function () {
},
proceed: {
text: 'Ok',
btnClass: 'btn btn-success',
action: function () {
var addUrl = "home/addsales";
addUrl += "/" + payment_type;
addUrl += "/" + cash_tendered;
addUrl += "/" + cust_name;
addUrl += "/" + amt_owed;
//
$.ajax({type: 'GET', url: addUrl, data: {},
success: function (result) {
$.alert({
content: result
});
$("#eType").val("");
$("#eCash").val("");
$("#cust_name").val("");
$("#amt_owed").val("");
location.reload();
},
error: function (xhr, status, error) {
$.alert({
content: 'Could not complete the process. ' + error
});
}
});
}
}
}
});
}
}
},
onContentReady: function () {
// bind to events
var jc = this;
this.$content.find('form').on('submit', function (e) {
// if the user submits the form by pressing enter in the field.
e.preventDefault();
jc.$$formSubmit.trigger('click'); // reference the button and click it
});
}
});
}
Here is the Home Controller Code:
private function addsales($payment_type = null, $cash_tendered = null, $cust_name = null, $amt_owed = null) {
if (isset($payment_type, $cash_tendered)) {
$email = $_SESSION[DbStrings::$EMAIL];
$payment_type = $this->test_input($payment_type);
$cash_tendered = $this->test_input($cash_tendered);
$insertedSale = $this->member->insertDailySale($email, $payment_type, $cash_tendered);
$cust_name = $this->test_input($cust_name);
$amt_owed = $this->test_input($amt_owed);
$insertedCredit = 1;
if (isset($cust_name, $amt_owed) && $amt_owed > 0) {
$insertedCredit = $this->member->insertCredit($email, $cust_name, $amt_owed);
}
if ($insertedSale && $insertedCredit) {
$_SESSION['temp_invoice'] = $_SESSION[DbStrings::$INVOICE];
$chars = "003232303232023232023456789";
srand((double) microtime() * 1000000);
$i = 0;
$pass = '';
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
$alpha = 'NM-' . $pass;
$_SESSION[DbStrings::$INVOICE] = $alpha;
echo "Your sale has been inserted succesfully";
} else {
echo "There was a problem inserting your sale. Please try again.";
}
} else {
echo 'Please fill all fields';
}
}
And Here is my Model Code that still fetches other functions:
public function insertDailySale($email, $payment_type, $cash_tendered) {
$invoice = $_SESSION[DbStrings::$INVOICE];
$this->db->from(DbStrings::$SALES_ORDER_TABLE_NAME);
$condition = array(DbStrings::$EMAIL => $email, DbStrings::$INVOICE => $invoice);
$this->db->where($condition);
$query = $this->db->get();
$checks = $query->result_array();
foreach ($checks as $queries) {
$productID = $queries[DbStrings::$PRODUCTID];
$quantity = $queries[DbStrings::$SALES_QUANTITY];
$amount = $queries[DbStrings::$SALES_AMOUNT];
$profit = $queries[DbStrings::$SALES_PROFIT];
$product_code = $queries[DbStrings::$PRODUCT_CODE];
$product_name = $queries[DbStrings::$PRODUCT_NAME];
$product_selling = $queries[DbStrings::$PRODUCT_SELLING];
$this->deductInventory($email, $product_code, $quantity);
$this->updateQuantitySold($email, $product_code, $quantity);
$cost_price = $this->product->getCostPrice($product_code);
$data[] = array(
DbStrings::$EMAIL => $email,
DbStrings::$INVOICE => $invoice,
DbStrings::$PRODUCTID => $productID,
DbStrings::$SALES_QUANTITY => $quantity,
DbStrings::$SALES_AMOUNT => $amount,
DbStrings::$SALES_PROFIT => $profit,
DbStrings::$PRODUCT_CODE => $product_code,
DbStrings::$PRODUCT_NAME => $product_name,
DbStrings::$PRODUCT_CP => $cost_price,
DbStrings::$PRODUCT_SP => $product_selling,
DbStrings::$PAYMENT_TYPE => $payment_type,
DbStrings::$CASH_TENDERED => $cash_tendered,
DbStrings::$DATE_CREATED => time()
);
$inserted = $this->db->insert_batch(DbStrings::$DAILYSALES_TABLE_NAME, $data);
}
return $inserted;
}
With the above, i get flagged this error:
There was a problem inserting your sale. Please try again.
Please I need help on this.
The error came from my database structure. Being an internal server error, it came from the DB.
I realized i deleted a column from my database table, and i was still sending data to the removed column.
Thanks guys for the attempt to help.
i have a live searcher thats when its data its shows
i need to alert if the data is empty
this is the jquery:
$(document).ready(function() {
$('#q').on('input', function() {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function(data) {
$('ul#content').show();
$('ul#content').empty()
$.each(data, function() {
if ( data.length == 0 ) {
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
}else{
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">' + this.title + '</font></li>');
}
});
}, "json");
}
});
});
and the php:
$conexion = mysqli_connect($serv,$user,$pass,$base);
$arr = array();
if (!empty($_POST['q'])) {
$keywords = $Main->limpiar($_POST['q']);
$mysqli = $conexion;
$result = $mysqli->query("SELECT cat, titulo FROM pinturas WHERE titulo LIKE '%".$keywords."%' OR cat LIKE '%".$keywords."%'");
if ($result->num_rows > 0) {
while ($obj = $result->fetch_array()) {
$seo = str_replace(" ","_",$obj['titulo']);
$arr[] = array('id' => $obj['cat'], 'title' => $obj['titulo'], 'seo' => $seo);
}
}else{
$arr[] = array('id' => '', 'title' => '', 'seo' => '');
}
}
echo json_encode($arr);
i want to if the data is empty shows the append empty
but it dont work
Assuming the data is a JSON parsed object you can:
Object.keys(data).length === 0
Or
JSON.stingify(data) === '{}'
Check length of the records before iteration (using $.each in jquery API)
<script>
$(document).ready(function () {
$('#q').on('input', function () {
var searchKeyword = $(this).val();
if (searchKeyword.length >= 3) {
$.post('/files/assets/php/ajax/search.php', { q: searchKeyword }, function (data) {
console.log(data);
$('ul#content').show();
$('ul#content').empty()
if (data.length == 0) {
$('ul#content').empty().append('<li style="text-align: center;font-weight:bold;"><font color="white">empty</font></a></li>');
}
else {
$.each(data, function () {
$('ul#content').append('<li style="text-align: center;font-weight:bold;"><font color="white">' + this.title + '</font></li>');
});
}
});
}
});
});
</script>
Worked for me.
Hope this helps.
I would like to ask a question and I need a little help from you guys.
I would like to use jquery Datatable plugin in my project but something going wrong.
The table is displayed properly, but none of the datatable functions working.
Here is my code:
function get_answer(get_date, get_id) {
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var date = get_date;
var id = get_id;
var data = {
'action': 'get_answers_ajax',
'date': date,
'id': id
};
var table_structure = '<table id="result-' + id + '" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#tabs-' + id).append(table_structure);
jQuery.post(ajaxurl, data, function (response) {
if (response) {
var obj = JSON.parse(response);
var heads = [];
var results = [];
jQuery.each(obj, function (key, res) {
if (jQuery.inArray(res.label, heads) == '-1')
{
heads.push(res.label);
}
results.push(res.value);
});
var head = jQuery('#tabs-' + id + ' .result_head tr');
head.empty();
jQuery.each(heads, function (key, value) {
head.append('<th>' + value + '</th>');
});
var body = jQuery('#tabs-' + id + ' .result_body');
body.empty();
if (results.length > 0) {
body.append('<tr role="row" class="odd">'); // Open tr
var count_heads = heads.length;
var count_answ = 0;
jQuery.each(results, function (key, value) {
if (value.substring(0, 4) == 'http') {
body.find('tr').last().append('<td><img src="' + value + '" alt="none" width="200px" height="200px" /></td>');
} else {
body.find('tr').last().append('<td>' + value + '</td>');
}
count_answ++;
if ((count_answ % count_heads) == 0) {
body.find('tr').last().find('td').last().after('</tr>');
body.find('tr').last().after('<tr role="row" class="even">');
}
});
body.find('tr').last().after('</tr>'); // Close tr
}
}
});
jQuery('#result-' + id).dataTable(
{
"ordering": true,
"searching": true
}
);
The heads and the reults array looks like this:
Heads => ["Eredmény", "Felhasználó", "Dátum"]
Results => ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"]
My PHP function which one gives back the data is this:
function get_answers() {
global $wpdb;
$date = $_POST['date'];
$form_id = $_POST['id'];
$date_pice = explode(' - ', $date);
$question = array();
$answer = array();
$sql_answers = "SELECT lead.date_created, detail.field_number, detail.value, detail.form_id, meta.display_meta FROM wp_rg_lead_detail AS detail INNER JOIN wp_rg_lead AS lead ON detail.lead_id = lead.id INNER JOIN wp_rg_form_meta AS meta ON detail.form_id = meta.form_id WHERE lead.date_created BETWEEN '{$date_pice[0]}' AND '{$date_pice[1]}' AND detail.form_id = '{$form_id}' ";
$answers = $wpdb->get_results($sql_answers);
foreach ($answers as $ans_info) {
$meta = self::bsp_unserialize($ans_info->display_meta);
foreach ($meta[fields] as $fields) {
if ($fields["id"] == $ans_info->field_number) {
$question["kerdes"] = $fields["label"];
$answer["valasz"] = $ans_info->value;
}
}
$toJSON[] = array("label" => $question["kerdes"], "value" => $answer["valasz"]);
}
echo json_encode($toJSON);
die();
}
So, the table shows all of the data in it, but If i would like to search or ordering or paginating nothings works.
Any hint about it?
Thx a lot
I could solve the problem.
I just modifed the append method, and now I making a html string with the ready html element and I jut append that at the end of the process.
jQuery(document).ready(function () {
var table_structure = '<table id="result" class="table table-striped table-hover table-dynamic display"><thead class="result_head"><tr><th></th></tr></thead><tbody class="result_body"><tr><td></td></tr></tbody></table>';
jQuery('#table').append(table_structure);
var heads = ["Result", "User", "Date"];
var results = ["666", "Wathfea", "2014-10-14 12:55:12", "hdjjdbkudbh", "Zsolti", "2014-10-14 16:44:55", "kfhkfvjhdgh", "Zsolti", "2014-10-14 17:16:29"];
jQuery('.result_head tr').empty();
jQuery.each(heads, function (key, value) {
jQuery('.result_head tr').append('<th>' + value + '</th>');
});
var body = jQuery('.result_body');
body.empty();
if (results.length > 0) {
var count_heads = heads.length;
var count_answ = 0;
var html = "";
jQuery.each(results, function (key, value) {
if ((count_answ % count_heads) === 0) {
html += '<tr>';
}
if (value.substring(0, 4) == 'http') {
html += '<td><img src="' + value + '" alt="none" width="200px" height="200px"/></td>';
} else {
html += '<td>' + value + '</td>';
}
count_answ++;
if ((count_answ % count_heads) === 0) {
html += '</tr>';
body.append(html);
html = '';
}
});
}
jQuery('#result').dataTable(
{
"ordering": true,
"searching": true
}
);
});
I am using a jQuery plugin called Stepy, which is based of the FormToWizard plugin, to allow users to complete a 10-step form.
Using the next/back attributes, I've added a function to post data between steps so the user can save their work and come back at a later day if they'd like.
One of my steps allows the user to add items to a form within an iframe (to post data to a separate table). I'd like it to function so that when the user moves between steps, the items in the iframe post to their separate table as well. Is there a way to submit the form within the iframe between steps (i.e. submit iframe sub-form when main form submits)?
I am using PHP and MySQL.
Any help you could provide would be amazing!
Javascript:
$(function() {
$('#custom').stepy({
backLabel: 'Back',
block: true,
errorImage: true,
nextLabel: 'Next',
titleClick: true,
validate: false,
legend: false,
back: function(index) {
$.post('../../process.php')
}
next: function(index) {
$.post('../../process.php')
}
});
});
HTML:
<html>
<body>
<form id="custom" name="custom">
<fieldset title="Thread 1">
<legend>description one</legend>
<label>Question A:</label>
<input type="text" id="question_a" name="question_a" class="required">
<label>Question B:</label>
<input type="text" id="question_b" name="question_b">
</fieldset>
<fieldset title="Thread 2">
<legend>description two</legend>
<iframe src="../../list_form.php" width="100%" height="300"></iframe>
</fieldset>
<fieldset title="Thread 3">
<legend>description three</legend>
<label>Question C:</label>
<input type="text" id="question_c" name="question_c" class="required">
</fieldset>
<input type="submit" class="finish" value="Finish!">
</form>
</body>
</html>
iframe
<html>
<body>
<form id="sub_form" name="sub_form">
<label>Question 1:</label>
<input type="text" id="question_1" name="question_1">
<label>Question 2:</label>
<input type="text" id="question_2" name="question_2">
</form>
</body>
</html>
stepy.js
;(function($) {
var methods = {
init: function(options) {
return this.each(function() {
var opt = $.extend({}, $.fn.stepy.defaults, options),
$this = $(this).data('options', opt),
id = $this.attr('id');
if (id === undefined) {
id = 'stepy-' + $this.index();
$this.attr('id', id);
}
var $titlesWrapper = $('<ul/>', { id: id + '-titles', 'class': 'stepy-titles' });
if (opt.titleTarget) {
$(opt.titleTarget).html($titlesWrapper);
} else {
$titlesWrapper.insertBefore($this);
}
if (opt.validate) {
$this.append('<div class="stepy-error"/>');
}
var $steps = $this.children('fieldset'),
$step = undefined,
$legend = undefined,
description = '',
title = '';
$steps.each(function(index) {
$step = $(this);
$step
.addClass('step')
.attr('id', id + '-step-' + index)
.append('<p id="' + id + '-buttons-' + index + '" class="' + id + '-buttons"/>');
$legend = $step.children('legend');
if (!opt.legend) {
$legend.hide();
}
description = '';
if (opt.description) {
if ($legend.length) {
description = '<span>' + $legend.html() + '</span>';
} else {
$.error(id + ': the legend element of the step ' + (index + 1) + ' is required to set the description!');
}
}
title = $step.attr('title');
title = (title != '') ? '<div>' + title + '</div>': '--';
$titlesWrapper.append('<li id="' + id + '-title-' + index + '">' + title + description + '</li>');
if (index == 0) {
if ($steps.length > 1) {
methods.createNextButton.call($this, index);
}
} else {
methods.createBackButton.call($this, index);
$step.hide();
if (index < $steps.length - 1) {
methods.createNextButton.call($this, index);
}
}
});
var $titles = $titlesWrapper.children();
$titles.first().addClass('current-step');
var $finish = $this.children('.finish');
if (opt.finishButton) {
if ($finish.length) {
var isForm = $this.is('form'),
onSubmit = undefined;
if (opt.finish && isForm) {
onSubmit = $this.attr('onsubmit');
$this.attr('onsubmit', 'return false;');
}
$finish.click(function(evt) {
if (opt.finish && !methods.execute.call($this, opt.finish, $steps.length - 1)) {
evt.preventDefault();
} else {
if (isForm) {
if (onSubmit) {
$this.attr('onsubmit', onSubmit);
} else {
$this.removeAttr('onsubmit');
}
var isSubmit = $finish.attr('type') == 'submit';
if (!isSubmit && (!opt.validate || methods.validate.call($this, $steps.length - 1))) {
$this.submit();
}
}
}
});
$finish.appendTo($this.find('p:last'));
} else {
$.error(id + ': element with class name "finish" missing!');
}
}
if (opt.titleClick) {
$titles.click(function() {
var array = $titles.filter('.current-step').attr('id').split('-'), // TODO: try keep the number in an attribute.
current = parseInt(array[array.length - 1], 10),
clicked = $(this).index();
if (clicked > current) {
if (opt.next && !methods.execute.call($this, opt.next, clicked)) {
return false;
}
} else if (clicked < current) {
if (opt.back && !methods.execute.call($this, opt.back, clicked)) {
return false;
}
}
if (clicked != current) {
methods.step.call($this, (clicked) + 1);
}
});
} else {
$titles.css('cursor', 'default');
}
$steps.delegate('input[type="text"], input[type="password"]', 'keypress', function(evt) {
var key = (evt.keyCode ? evt.keyCode : evt.which);
if (key == 13) {
evt.preventDefault();
var $buttons = $(this).parent().children('.' + id + '-buttons');
if ($buttons.length) {
var $next = $buttons.children('.button right-aligned');
if ($next.length) {
$next.click();
} else {
var $finish = $buttons.children('.finish');
if ($finish.length) {
$finish.click();
}
}
}
}
});
$steps.first().find(':input:visible:enabled').first().select().focus();
});
}, createBackButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-back-' + index, href: 'javascript:void(0);', 'class': 'button left-aligned', html: opt.backLabel }).click(function() {
if (!opt.back || methods.execute.call($this, opt.back, index - 1)) {
methods.step.call($this, (index - 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, createNextButton: function(index) {
var $this = this,
id = this.attr('id'),
opt = this.data('options');
$('<a/>', { id: id + '-next-' + index, href: 'javascript:void(0);', 'class': 'button right-aligned', html: opt.nextLabel }).click(function() {
if (!opt.next || methods.execute.call($this, opt.next, index + 1)) {
methods.step.call($this, (index + 1) + 1);
}
}).appendTo($('#' + id + '-buttons-' + index));
}, execute: function(callback, index) {
var isValid = callback.call(this, index + 1);
return isValid || isValid === undefined;
}, step: function(index) {
index--;
var $steps = this.children('fieldset');
if (index > $steps.length - 1) {
index = $steps.length - 1;
}
var opt = this.data('options');
max = index;
if (opt.validate) {
var isValid = true;
for (var i = 0; i < index; i++) {
isValid &= methods.validate.call(this, i);
if (opt.block && !isValid) {
max = i;
break;
}
}
}
$steps.hide().eq(max).show();
var $titles = $('#' + this.attr('id') + '-titles').children();
$titles.removeClass('current-step').eq(max).addClass('current-step');
if (this.is('form')) {
var $fields = undefined;
if (max == index) {
$fields = $steps.eq(max).find(':input:enabled:visible');
} else {
$fields = $steps.eq(max).find('.error').select().focus();
}
$fields.first().select().focus();
}
if (opt.select) {
opt.select.call(this, max + 1);
}
return this;
}, validate: function(index) {
if (!this.is('form')) {
return true;
}
var $step = this.children('fieldset').eq(index),
isValid = true,
$title = $('#' + this.attr('id') + '-titles').children().eq(index),
opt = this.data('options'),
$this = this;
$($step.find(':input:enabled').get().reverse()).each(function() {
var fieldIsValid = $this.validate().element($(this));
if (fieldIsValid === undefined) {
fieldIsValid = true;
}
isValid &= fieldIsValid;
if (isValid) {
if (opt.errorImage) {
$title.removeClass('error-image');
}
} else {
if (opt.errorImage) {
$title.addClass('error-image');
}
$this.validate().focusInvalid();
}
});
return isValid;
}
};
$.fn.stepy = function(method) {
if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments);
} else {
$.error('Method ' + method + ' does not exist!');
}
};
$.fn.stepy.defaults = {
back: undefined,
backLabel: '< Back',
block: false,
description: true,
errorImage: false,
finish: undefined,
finishButton: true,
legend: true,
next: undefined,
nextLabel: 'Next >',
titleClick: false,
titleTarget: undefined,
validate: false,
select: undefined
};
})(jQuery);
If you want to append Text\HTML or any other data to your iframe (which calling to a page on the same domain!) you may use:
jQuery("#iframe_id").contents().find('body').append('<div>Hello World</div>');
Full Example:
Full Example
If your iframe is on another domain you will have to use window.postMessage, which you may read about on Mozilla's docs:
Mozilla's docs
OR to take a look about my blog post about this subject.
Hope I helped,