Trigger autocomplete for the field of the modal that is active - javascript

The scenario here is that on the several pages I am having modals that have a autocomplete search field. so instead of giving several different IDs to each field, and then triggering them, I used a common class and tried to trigger autocomplete() on the field that resides in modal with .activeModal class.
function customerSearch() {
$(".activeModal .customerSearch").autocomplete({
minLength: 1,
focus: function(event, ui) {
event.preventDefault();
$(".activeModal .customerSearch").val(ui.item.label);
},
source: function(request, response) {
$.ajax({
url: "/operations.php",
dataType: "json",
type: "post",
data: {
"req": "searchCustomer",
"query": $(".activeModal .customerSearch").val(),
},
success: function(data) {
response($.map(data, function(item) {
return {
id: item.id,
label: item.label,
value: item.value
}
}));
}
})
},
select: function(event, ui) {
event.preventDefault();
$(".activeModal .customerSearch").val(ui.item.label);
$(".activeModal .customer_id").val(ui.item.value);
}
})
}
$(document).ready(function() {
customerSearch();
});
However this is not working; it's not showing any results. Neither is it giving any errors when I checked the browser console.
What have I done wrong? I am new to jQueryUI so please spare me for silly mistakes.
EDIT : The question seems to be confusing many people, so; for example, here are 3 modals that have fields with same purpose on the same page:
<div class="modal" id="newGiftcard">
<div class="head">
<span class="modalTitle">
Issue new giftcard
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<form id="newGiftCardForm">
<input type="text" name="customer" placeholder="Search customer" class="ui-widget customerSearch" id="customerSearch" />
<input type="hidden" class="customer_id" id="customer_id"/>
<input type="checkbox" id="walkinGC" class="walkin" /><label for="walkinGC"> Walk in</label>
<input type="text" id="cardNumber" placeholder="Gift card number" />
<input type="text" id="balance" placeholder="Balance" />
<select id="payMethod">
<option value="">Select a payment mode</option>
<option value="cash">cash</option>
<option value="card">card</option>
<option value="cheque">cheque</option>
</select>
<button type="button" id="IssueGC">Issue</button>
<button type="reset" class="grey">Reset</button>
</form>
</div>
</div>
<div class="modal" id="addBalance">
<div class="head">
<span class="modalTitle">
add balance
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<p>please enter the amount:</p>
<form>
<input type="hidden" id="card" />
<input type="text" placeholder="amount" id="amount" />
<select id="payMethod">
<option value="">Select a payment mode</option>
<option value="cash">cash</option>
<option value="card">card</option>
<option value="cheque">cheque</option>
</select>
<button type="button" id="addBal">Add balance</button>
</form>
</div>
</div>
<div class="modal" id="changeOwner">
<div class="head">
<span class="modalTitle">
add balance
</span>
<span class="controller">
<span class="close lnr lnr-cross"></span>
</span>
</div>
<div class="main">
<p>please enter the amount:</p>
<form>
<input type="hidden" id="card" />
<input type="text" name="customer" placeholder="Search customer" class="ui-widget customerSearch"/>
<input type="hidden" class="customer_id"/>
<input type="checkbox" id="walkinGC" class="walkin" /><label for="walkinGC"> Walk in</label>
<button type="button" id="changeOW">Add balance</button>
</form>
</div>
</div>

Related

get value from form select and then calculate value in an input

I am trying to calculate multiple values based on multiple selections from a and then have the data add up and display in an on the same form. I tried some jquery stuff but didn't really work at all. I've tried using some Javascript to do the calcultions but nothing seems to be happening.
Blade:
#extends('layout.layouts')
#section('content')
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>NCIC - Reports</title>
</head>
<body>
<br>
<h1>New Report</h1>
<br>
<form action="{{ 'storereport' }}" method="POST" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
<div class="form-group">
<label for="author">Reporting Officer</label>
<input type="text" class="form-control" name="author" value="{{ Auth::user()->name }}">
</div>
<div class="form-group">
<label for="profileid">SSN</label>
<input type="text" class="form-control" name="profileid">
</div>
<div class="form-group">
<label for="report">Report</label>
<textarea class="form-control" name="report" rows="10"></textarea>
</div>
<div class="form-group">
<label for="selectpicker">Select Offences</label>
<select class="selectpicker" id="lawspicker" name="laws[]" data-width="100%" data-live-search="true" multiple>
#foreach($laws as $law)
<option value="{{ $law->name }} {{ $law->fine }} {{ $law->months }}">Offence: {{ $law->name }} </option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment">
</div>
<hr style="background-color:white;">
<button type="submit" class="btn btn-success">Submit</button>
<a class="btn btn-info float-right" href="{{ route('reports') }}">Main menu</a>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$("#lawspicker").keyup(function(){
$("#punishment").val(parseFloat($("{{ $law->months }}").val()) + parseFloat($('{{ $law->fine }}').val()));
})
$("#lawspicker").change(function(){
$("#punishment").val(parseInt($("#lawspicker").val());
})
</script>
<style>
body{
background-color: #353b48;
color:white;
}
</style>
</html>
#endsection
To clarify, I want {{ $law->months }} & {{ $law->fine }} to add up and then display in #punishment <input>
Thanks for looking!
You can do some thing like this.
Update <option> tag to this
<option data-fine="{{$law['fine']}}" data-months="{{$law['months']}}" value="{{ $law['name'] }} {{ $law['fine'] }} {{ $law['months'] }}">Offence: {{ $law['name'] }} </option>
and you can get data attribute of the selected <option> tag in your script like this.
`$("#lawspicker").change(function() {
var fine = $(this).find(':selected').data('fine');
let months = $(this).find(':selected').data('months');
$("#punishment").val(parseInt(fine+months));
});`
Thanks.
I would be tempted to replace your select element with checkboxes personally.
An example below using jquery to calculate the fine and months when a button is clicked but could be an event of your choosing. I stripped it back from your example so it was easier to see what is going on.
Checkbox example
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="form-group">
<h4>Select Offences</h4>
<div class="d-flex">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-a" data-fine="100" data-months="12" class="custom-control-input offence">
<label for="law-a" class="custom-control-label">Law A</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-b" data-fine="999" data-months="6.5" class="custom-control-input offence">
<label for="law-b" class="custom-control-label">Law B</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" name="laws[]" id="law-c" data-fine="123.5" data-months="8" class="custom-control-input offence">
<label for="law-c" class="custom-control-label">Law C</label>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment" readonly>
</div>
</div>
<div class="col-12">
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
Then some javascript (jquery)
$(function() {
$("#submit").click(function() {
let fine = 0;
let months = 0;
$(".offence").each(function(index, obj) {
if (obj.checked) {
fine += parseFloat($(obj).data("fine"));
months += parseFloat($(obj).data("months"));
}
})
$("#punishment").val("Fine: "+ fine + " Months: " + months);
})
});
When you click submit, the javascript will loop through each element with the offence class and then read the value of the data-fine and calculate the totals.
An example fiddle: https://jsfiddle.net/dbtas60w/
Multiselect example
<div class="container mt-4">
<div class="row">
<div class="col-12">
<div class="form-group">
<h4>Select Offences</h4>
<div class="d-flex">
<div class="custom-control custom-checkbox">
<select class="selectpicker" id="lawspicker" name="laws[]" multiple>
<option data-fine="100" data-months="12">Law A</option>
<option data-fine="999" data-months="6.5">Law B</option>
<option data-fine="123.5" data-months="8">Law C</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-12">
<div class="form-group">
<label for="punishment">Punishment</label>
<input type="text" class="form-control" id="punishment" name="punishment" readonly>
</div>
</div>
<div class="col-12">
<button type="submit" id="submit" class="btn btn-primary">Submit</button>
</div>
</div>
</div>
javascript
$(function() {
$("#submit").click(function() {
let fine = 0;
let months = 0;
$("#lawspicker>option").each(function(index, obj) {
if (obj.selected) {
fine += parseFloat($(obj).data("fine"));
months += parseFloat($(obj).data("months"));
}
})
$("#punishment").val("Fine: "+ fine + " Months: " + months);
})
});
Example fiddle: https://jsfiddle.net/dbtas60w/1/

How to store an incomplete multi-step form?

I currently have a form that is multi-step; it doesn't do anything fancy per step, it simply does display: none on the previous step to hide the previous fields and move the user forward.
It submits via AJAX and has required fields.
Is there any way to capture the data from each step of the form, and then, if the user drops off or never submits the form, send the captured data - I'm not worried about any issues in regards to data protection, as it doesn't apply in this situation.
The form basically looks like this:
<form>
<div class="step-1">
<label>First Field
<input type="text" id="field1" name="field1" maxlength="50">
</label>
<label>Second Field
<input type="text" id="field2" name="field2" maxlength="50">
</label>
next step
</div>
<div class="step-2">
<label>Third Field
<input type="text" id="field3" name="field3" maxlength="50">
</label>
<label>Fourth Field
<input type="text" id="field4" name="field4" maxlength="50">
</label>
<input type="submit" id="send" name="submit" />
<span id="submitdata"></span>
</div>
</form>
The bit I'm struggling with is knowing when the user drops... Does it need to invoke some kind of session per the form?
You could automatically submit the form when the user leaves the page, using the beforeUnload event:
var notSubmitted = true;
$('form').on('submit', function() { notSubmitted = false; });
$(window).on("beforeunload", function() {
return notSubmitted ? $('form').submit() : null;
})
$("form").submit(function (e) {
e.preventDefault();
// ... ajax submission goes here ...
return false;
});
If you need to record that it is a 'by default' submission, then you could use a hidden form element instead of the variable notSubmitted. The hidden element would give you that data in the form.
Try this code:
$(document).ready(function () {
//alert("hi");
setTimeout(function () {
$("#msg").hide(1000);
}, 3000);
$("form#product_form").submit(function (e) {
//alert('hi');
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '<?php echo site_url('C_home/pro_add'); ?>',
type: "POST",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function (result) {
//alert(result);
$("#product_form").trigger('reset');
window.location.href = "<?php echo site_url('C_home/data_tbl'); ?>";
}
});
return false;
});
$("#product_form").validate({
rules: {
name: "required",
category_id: "required",
image: "required",
description: "required",
qty: "required",
price: "required"
},
messages: {
name: "Product name is required",
category_id: "Please Select Category name",
image: "Plases Select Product Image",
description: "Product Description is required",
qty: "Product Quantity is required",
price: "Product Price is required",
}
})
});
<script src="<?php echo base_url(); ?>assets/js/jquery.bootstrap.wizard.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.validate.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/wizard.js"></script>
<div class="wizard-container">
<div class="card wizard-card ct-wizard-orange" id="wizard">
<form id="product_form" method="POST" enctype="multipart/form-data">
<div class="wizard-header">
<h3>
Jquery Accordion
</h3>
</div>
<ul>
<li>Product Panel 1</li>
<li>Product Panel 2</li>
<li>Product Panel 3</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="about">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Product Name" required="" />
</div>
<div class="form-group">
<label>Select Category</small></label>
<select class="form-control" id="category_id" name="category_id" required="">
<option></option>
<!-- <option>--Select Category Name--</option> -->
<?php
foreach ($category as $row) {
?>
<option value="<?php echo $row['category_id']; ?>"><?php echo $row['category_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="account">
<div class="row">
<div class="col-sm-4 col-sm-offset-1">
<div class="picture-container">
<div class="picture">
<img src="<?php echo base_url(); ?>assets/img/default-avatar.png" style="height: 100px;" class="picture-src" id="wizardPicturePreview" title=""/>
<input type="file" class="form-control" name="image" id="wizard-picture" required="">
</div>
<h6>Choose Picture</h6>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Product Description</label>
<textarea class="form-control" name="description" id="description" placeholder="Enter Product Description" rows="5" required></textarea>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="address">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Qty</label>
<input type="text" class="form-control" name="qty" id="qty" placeholder="Enter Product Qty" required />
</div>
<div class="form-group">
<label>Product Price</label>
<input type="text" class="form-control" name="price" id="price" placeholder="Enter Product Price" required />
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<button type='button' class='btn btn-next btn-fill btn-warning btn-wd btn-sm' name='next' id="next" />Next</button>
<button type='submit' class='btn btn-finish btn-fill btn-warning btn-wd btn-sm' name='submit' value='Submit' />Submit</button>
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd btn-sm' name='previous' id="prev" value='Previous' />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div>

How to check which checkbox is checked and save the data into database using Angular

I have 4 different checkboxes and when I check one(or two, or three, or all) I want to save some data into a database with a click on the button "Save". I'm using angular.
How I can do this?
I have this HTML code:
<div class="addMode1" style="display: none;">
<div class="form">
<form ng-submit="createReason(reasonsForm1.$valid)" name="reasonsForm1">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<label for="database_address">Name of reason:</label>
<input type="text" class="form-control" ng-model="reasonname" placeholder="Име основание за добавяне" />
</div>
<div class="container">
<p>Using in::</p>
<input type="checkbox" ng-model="all">Buy<br>
<input type="checkbox" ng-checked="all">Sell<br>
<input type="checkbox" ng-checked="all">PKO<br>
<input type="checkbox" ng-checked="all">RKO
</div>
</div>
</div>
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-primary" id="cnlbtn1" type="button">Cancel</button>
<!--ng-click="createUser()"-->
<!--<button class="btn btn-primary" ng-disabled="userForm.$invalid" type="submit">Добавяне на нов</button>-->
</form>
</div>
</div>
And Angular code(createReason function which saves data from input box into the database):
$scope.createReason=function()
{
var objectToSave = {
name: $scope.reasonname,
};
defaultAdapter.query('INSERT INTO reasons(name) VALUES(:name)',
{ replacements: objectToSave, type: Sequelize.QueryTypes.UPDATE }
).then(projects => {
console.log(projects);
$scope.editMode = false;
$scope.activeItem = false;
$scope.refresh();
});
}
Please help me.
Thanks!
enter image description here
<label><input type="checkbox" name="test" ng-model="testModel['item1']" /> Testing</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item2']" /> Testing 2</label><br />
<label><input type="checkbox" name="test" ng-model="testModel['item3']" /> Testing 3</label><br />
After this on submit check the testModel index value which one is true or false then send that value in database.
try this i hope its helpful to you

Jquery get value of select in div above

I have the following HTML form. I'm trying to get the value of the .plotNumber select and also the value of the sub_category field.
Note: The user is able to add new rows to the form, so there may be multiple blocks of <div class="standard-row add-admin-row input-row">.
My code so far (which works) apart from the plot and category is:
$('.wrapper').on('input', '.inp-calculate', function(e)
{
var input = $(this);
//var plot = input.val(); // get plot id
//var category = input.val(); // get category id
var units = input.val(); // get units
$.post('checkUnits.php', {
plot_id: plot,
category_id: category,
units: units
}, function(data) {
var data = $.parseJSON(data);
if(data[0] !== true) {
alert(data);
input.focus();
input.val('');
}
});
});
I have tried the following solutions which do not work:
$(this).parent().siblings().find('.plotNumber').val();
HTML Code:
<form class="commentForm add-project-form clearfix" id="addWorksheet">
<div class="box box3 clearfix">
<div id="messages"></div>
<div class="sectionbox">
<fieldset class="clonable">
<legend><span>Worksheet</span></legend>
<p class="error-summary error-message"></p>
<div class="standard-row add-admin-row input-row">
<label class="ib">
<span class="label-stacked">Employee</span>
<span class="plain-select">
<select class="inp" data-myname="worksheet[*][employee]" name="employee">
<option value="">Select one...</option>
<option value="1">Test 1</option>
</select>
</span>
</label>
<label class="ib">
<span class="label-stacked">Week ending</span>
<span class="plain-select">
<select class="inp" data-myname="worksheet[*][week_ending]" name="week_ending">
<option value="">Select one...</option>
<option value="Sunday 22 Nov 2015">Sunday 22 Nov 2015</option>
</select>
</span>
</label>
<label class="ib">
<span class="label-stacked">Project</span>
<span class="plain-select">
<select class="inp project" data-myname="worksheet[*][project]" name="project">
<option value="">Select one...</option>
<option value="2">TEST</option>
</select>
</span>
</label>
</div>
<div class="standard-row wsheet-row input-row">
<label class="ib plothead ">
<span class="label-stacked">Plot Number</span>
<span class="plain-select">
<select class="inp plotNumber plotheadclone" data-myname="worksheet[*][plots][!][plot_number]" name="plot_number">
<option value="">Select one...</option>
<option value="6672">444</option>
<option value="6673">555</option>
<option value="6674">666</option>
</select>
</span>
</label>
<div class="plot-offset clearfix">
<div class="standard-row wsheet-row input-row" id="5438">
<label class="ib">
<span class="label-stacked">Category</span>
<select class="inp inp220 inp-disabled" readonly="" data-myname="worksheet[*][plots][!][sub_category][]" name="sub_category">
<option value="5438">NON LABOUR</option>
</select>
</label>
<label class="ib"><span class="label-stacked">Total</span>
<input class="inp inp110 data-addup-total inp-calculate" data-myname="worksheet[*][plots][!][total_cost][]" name="total_cost" value="0.00" type="text">
<input data-myname="worksheet[*][plots][!][price][]" name="price" value="" type="hidden">
<input data-myname="worksheet[*][plots][!][number_units][]" name="number_units" value="" type="hidden">
</label>
</div>
<div class="standard-row wsheet-row input-row" id="5240">
<label class="ib">
<span class="label-stacked">Category</span>
<select class="inp inp220 inp-disabled" readonly="" data-myname="worksheet[*][plots][!][sub_category][]" name="sub_category">
<option value="5240">1ST FIX CYLINDER</option>
</select>
</label>
<label class="ib">
<span class="label-stacked">Price</span>
<input class="inp inp110 inp-disabled" readonly="" data-myname="worksheet[*][plots][!][price][]" name="price" value="£40.00" type="text"></label>
<label class="ib"> <span class="label-stacked">Number</span>
<input class="inp inp55 inp-calculate" data-myname="worksheet[*][plots][!][number_units][]" name="number_units" value="" type="text"></label><label class="ib"><span class="label-stacked">Total</span><input class="inp inp110 inp-disabled data-addup-total" readonly="" data-myname="worksheet[*][plots][!][total_cost][]" name="total_cost" value="£0.00" type="text"></label>
</div>
<div class="wsheet-labour-total">LABOUR: £80.00</div>
<div class="wsheet-nonlabour-total">NON LABOUR: £0.00</div>
<div class="wsheet-final-total">TOTAL CLAIM: £80.00</div>
</div>
</div>
</fieldset>
<div class="reveal-plot showingPlot"> Choose another plot</div>
</div>
<!-- end section box -->
<hr class="divider">
<div class="clonable">
<div class="clone empty"></div>
<div class="cb">
<div>
<p class="add remove-data"><i class="sprite minus2"></i> <span>Remove last row</span></p>
</div>
<div>
<p class="add add-data add-another-worksheet-employee"><i class="sprite plus2"></i> <span>Add another worksheet</span></p>
</div>
</div>
</div>
<div class="save-submit">
<button class="button" type="submit" data-url="addWorksheet.php" data-id="#addWorksheet">Submit</button>
</div>
</div>
<!-- end box -->
</form>
Can someone help find the solution?
You're not traversing far enough up the DOM with .parent() since the select is contained in a <div> three levels above .inp-calculate. How about:
$(this).closest('fieldset').find('.plotNumber').val();
Try like following. Hope this will help you.
var container=$(this).closest('.standard-row.add-admin-row.input-row');
var plot=container.find('.plotNumber').val();
var category=container.find('.inp220').val();

possible to make ajax call for 2 links with one function

When I click fetch, I need the data to be fetched but not displayed in the form, but when I click feeling lucky, i want to display the list and fill up the form.
I got the logic working well for fetch link, Do I have to repeat the same for feeling lucky link? is there a optimized way to do it.
$post-item-# click event is inside success call data each loop, is that the right place to do it?
Here's a mirror of the snippet below: JSFiddle
Data
{
tag: "urlfoodchannel,chocolate,dessert",
searchedTags: "urlfoodchannel,chocolate,dessert|urlfoodchannel,chocolate,dessert|urlfoodchannel,chocolate,dessert",
tagPage: "/food/urlfoodchannel,chocolate,dessert-recipes/",
page: "2",
pages: "2",
total: "20",
posts: [{
postId: "21122896",
postUrl: "/article/2014/12/30/chocolate-oreo-ice-cream/21122896/",
postTitle: "Chocolate Oreo Ice Cream",
postExcerpt: "This creamy chocolate ice cream with chunks of Oreo cookie is perfect and surprisingly easy to make!",
postAuthor: "Marin Mama Cooks",
postPubdate: "2014-12-30T20:49:00",
postPubdateUnix: "1419990540",
postImage: "http://urlcdn.com/hss/storage/midas/201316424/chocolate-oreo-ice-cream-11.jpg"
} {
postId: "21122797",
postUrl: "/article/2014/12/30/sheet-pan-smores/21122797/",
postTitle: "Sheet Pan S'mores",
postExcerpt: "You've never had s'mores quite like this! Try this decadent and delicious recipe for sheet pan s'mores.",
postAuthor: "Oh, Bite It",
postPubdate: "2014-12-30T15:26:00",
postPubdateUnix: "1419971160",
postImage: "http://urlcdn.com/hss/storage/midas/201315673/spsbet.jpg"
}]
}
Script
$(document).ready(function () {
$("#fetch").on("click", function () {
tags = $("#tags").val();
count = $("#count").val() ? $("#count").val() : "10";
page = $("#page").val() ? $("#page").val() : "1";
apiurl = "http://urlblog.url.com/api/tags-v1/" + tags + "?pageSize=" + count + "&page=" + page;
$.ajax({
type: 'GET',
url: apiurl,
data: {
get_param: 'value'
},
success: function (data) {
$("#tag").text(data.tagPage);
$.each(data.posts, function (i) {
$("#posts").append('<li class="post-item-' + i + '"><p class="post-title">' + data.posts[i].postTitle + ' <img class="add-row" src="/portalcms/_tool/media/add.png">+</p><p class="post-thumb"><img src="' + data.posts[i].postImage + '" width="150px" class="post-image"/></p><p class="post-url">' + data.posts[i].postUrl + '</p></li>');
$(".post-item-" + i).bind("click", function () {
k = i + 1;
tval = $(this).find(".post-title").text();
ival = $(this).find(".post-image").attr("src");
uval = $(this).find(".post-url").text();
$("#input-link" + k + "\\.alt").val(tval);
$("#input-link" + k + "\\.href").val(uval);
$("#input-link" + k + "\\.credit").val(ival);
});
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<fieldset class="visible">Tags for tomorrow:
<input type="text" name="futuretags" id="future-tags" />
</fieldset>
<fieldset class="visible">Tags:
<input type="text" name="tags" id="tags" value="" />Count:
<input type="text" name="count" id="count" value="10" />Page:
<input type="text" name="page" id="page" value="1" /> Fetch
Feeling Lucky
<ul id="posts"></ul>
</fieldset>
<fieldset>
<legend>Link 1:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link1.src._action">Image:</label>
<br />
<select id="input-link1.src._action" name="link1.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link1.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link1.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link1.alt">Alt Text:</label>
<input id="input-link1.alt" type="text" name="link1.alt" value="" />
</li>
<li class="">
<label for="input-link1.credit">Credit:</label>
<input id="input-link1.credit" type="text" name="link1.credit" value="" />
</li>
<li class="">
<label for="input-link1.href">Href (URL):</label>
<input id="input-link1.href" type="text" name="link1.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link1.target">Target:</label>
<select id="input-link1.target" name="link1.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link1.onclick">Onclick:</label>
<input id="input-link1.onclick" type="text" name="link1.onclick" value="" />
</li>
<li class="">
<label for="input-link1.otherAtts">Other Attributes:</label>
<input id="input-link1.otherAtts" type="text" name="link1.otherAtts" value="" />
</li>
<li class="">
<label for="input-link1.trackKey">Tracking Key:</label>
<select id="input-link1.trackKey" name="link1.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link1.trackVal">Tracking Value:</label>
<input id="input-link1.trackVal" type="text" name="link1.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset>
<fieldset>
<legend>Link 2:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link2.src._action">Image:</label>
<br />
<select id="input-link2.src._action" name="link2.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link2.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link2.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link2.alt">Alt Text:</label>
<input id="input-link2.alt" type="text" name="link2.alt" value="" />
</li>
<li class="">
<label for="input-link2.credit">Credit:</label>
<input id="input-link2.credit" type="text" name="link2.credit" value="" />
</li>
<li class="">
<label for="input-link2.href">Href (URL):</label>
<input id="input-link2.href" type="text" name="link2.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link2.target">Target:</label>
<select id="input-link2.target" name="link2.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link2.onclick">Onclick:</label>
<input id="input-link2.onclick" type="text" name="link2.onclick" value="" />
</li>
<li class="">
<label for="input-link2.otherAtts">Other Attributes:</label>
<input id="input-link2.otherAtts" type="text" name="link2.otherAtts" value="" />
</li>
<li class="">
<label for="input-link2.trackKey">Tracking Key:</label>
<select id="input-link2.trackKey" name="link2.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link2.trackVal">Tracking Value:</label>
<input id="input-link2.trackVal" type="text" name="link2.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset>
<fieldset>
<legend>Link 3:</legend>
<ul class="inputs">
<li class="compact quickFormField-file ">
<label for="input-link3.src._action">Image:</label>
<br />
<select id="input-link3.src._action" name="link3.src._action">
<option value="no">No File</option>
<option value="upload">Upload a New File:</option>
<option value="url">Use File at Asset URL:</option>
</select> <span class="upload" style="display: none;"><input type="file" name="link3.src._upload" /></span>
<span class="url" style="display: none;"><input type="text" name="link3.src._url" value="" /> <small>(e.g. /path/to/file.jpg)</small></span>
</li>
<li class="">
<label for="input-link3.alt">Alt Text:</label>
<input id="input-link3.alt" type="text" name="link3.alt" value="" />
</li>
<li class="">
<label for="input-link3.credit">Credit:</label>
<input id="input-link3.credit" type="text" name="link3.credit" value="" />
</li>
<li class="">
<label for="input-link3.href">Href (URL):</label>
<input id="input-link3.href" type="text" name="link3.href" value="" />
</li>
</ul>
<div class="advancedgrp">
<div class="hdr">Show Advanced Options</div>
<fieldset class="cnt">
<legend>Advanced Options:</legend>
<ul class="inputs">
<li class="">
<label for="input-link3.target">Target:</label>
<select id="input-link3.target" name="link3.target">
<option value="">Same Window</option>
<option value="_blank">New Window</option>
</select>
</li>
<li class="">
<label for="input-link3.onclick">Onclick:</label>
<input id="input-link3.onclick" type="text" name="link3.onclick" value="" />
</li>
<li class="">
<label for="input-link3.otherAtts">Other Attributes:</label>
<input id="input-link3.otherAtts" type="text" name="link3.otherAtts" value="" />
</li>
<li class="">
<label for="input-link3.trackKey">Tracking Key:</label>
<select id="input-link3.trackKey" name="link3.trackKey">
<option value="icid" selected="selected">icid</option>
<option value="ncid">ncid</option>
</select>
</li>
<li class="">
<label for="input-link3.trackVal">Tracking Value:</label>
<input id="input-link3.trackVal" type="text" name="link3.trackVal" value="" />
</li>
</ul>
</fieldset>
</div>
<ul class="inputs"></ul>
</fieldset> <span id="tag"></span>
What you can do is just write the javascript function like this:
$(function(){
var searchmethods = {
fetched : false,
data : "",
fetch : function(callback) {
$.ajax({
success: function(data) {
fetched = false;
searchmethods.data = data;
if($.isFunction(showResults)) showResults();
}
});
},
lucky : function() {
if(searchmethods.fetched) {
searchmethods.showResults();
} else {
searchmethods.fetch(searchmethods.showResults);
}
},
showResults : function() {
// show results
}
};
$(".link").click(function(){
var action = $(this).data("action");
searchmethods[action].apply(this);
});
});
i like this way because you have all the code that you are going to need into an object
called searchmethods and it has the methods. Here is how does this work:
searchmethods.fetch() is called when you click on the fetch link, and retrieves the
data with the jQuery $.ajax() method.
searchmethods.lucky() is called when you click on the lucky link, checks if the data has been
retrieved, if not then it calls the searchmethods.fetch() method an it passes the function searchmethods.lucky() by parameter so it can be called after the $.ajax() retrieves the data
and the HTML like this:
<a data-action="fetch" class="link">fetch</a>
<a data-action="lucky" class="link">lucky</a>
but it is up to you, that's just an easy way
EDIT: answer it's already updated, sorry about my weird english

Categories