Send selected data back to original window - javascript

I have a file called bpSearch. Inside bpSearch, I have a MODAL window, called addNewModal. Within addNewModal, I have 2 INPUT fields called partnerName and partnerCode. I have a button that once clicked, opens into another MODAL window, called searchPartnerModal.
Here is the a portion of the FORM inside addNewModal:
<form action="bpSearch.php" method="get">
<input type="text" readonly id="partnerName" name="partnerName" />
<input type="text" readonly id="partnerCode" name="partnerCode" />
Go
</form>
When the user clicks GO, it opens searchPartnerModal.
searchPartnerModal is where the user will enter either a code or a name (doesn't have to be both). But upon hitting SEARCH, I use an AJAX call that returns JSON that I parse and eventually return in a UL field called pNames. We're still inside searchPartnerModal.
Here is the FORM inside searchPartnerModal:
<form action="bpSearch.php" method="get">
<input type="text" id="pNameSearch" name="pNameSearch" />
<input type="text" id="pCodeSearch" name="pCodeSearch" />
<input type="button" class="btn" id="pSearch" name="pSearch" value="search" />
</form>
When the user enters a name, I use jquery to send it over to a PHP script that will then return the data in a UL tag.
Here is the jquery that will search if the user enters a name:
$('#pSearch').on('click', function()
{
var partnername = $('#pNameSearch').val();
if($.trim(partnername) != '')
{
$.post('api/pNameSearch.php', {partnername: partnername}, function(data)
{
var obj = JSON.parse(data);
$('#pNames').empty();
var htmlToInsert = obj.map(function (item)
{
return '<li><a id="getPInfo" href="javascript:;"
onclick="getPInfo()" data-selname="'+item.FULL_NAME+'"
data-selcode="'+item.PARTNER_CODE+'">'
+ item.FULL_NAME + ' - '
+ item.PARTNER_CODE + '</a></li>';
}).join('');
$('#pNames').html(htmlToInsert);
});
};
});
With this code, I am able to send the name to search the database table for a valid name. The data is returned via JSON and is parsed and displayed inside the UL tag (called pNames) as LI tags, each with an A tag with their own data-attributes, called data-selname and data-selcode.
Now what I need to do is once the user clicks on one of the returned data links inside pNames, I need to send it back to the previous modal window, addNewModal.
This is where I'm stuck.
If you look inside the Jquery above, after I parsed the JSON, you will see that I created another Javascript function inside the A tag of each returned piece of data, called getPInfo().
Here is what I got so far for the function getPInfo() :
function getPInfo()
{
var selname = ($('#getPInfo').attr('data-selname'));
var selcode = ($('#getPInfo').attr('data-selcode'));
}
At this point, I can alert both variables (selname and selcode) and get them to display in an alert window.
What I want to do is send both of those variables back to addNewModal in the respective INPUT fields, called partnerName and partnerCode.
So selname will go to partnerName and selcode will go to partnerCode.
I didn't display the PHP script that returned the data.

Change the anchor id=getPInfo to class=getPInfo since you have multiple anchors. Next, handle the click event of the anchor and extract the data attributes and set the corresponding form elements in the addNewModal form. Following should work based on the markup i see so far.
$(function(){
$('body').on('click', 'a.getPInfo', function (e) {
var $a = $(e.srcElement || e.target);
$('#partnerName').val($a.attr('data-selname'));
$('#partnerCode').val($a.attr('data-selcode'));
$('#searchPartnerModal').modal('hide'); //assuming bootstrap modal
});
});

Related

Jquery refresh & remove "hidden" attribute by clicking on a button

This is my code:
Html
<div class="tracking-id">
<input type="text" id="tracking_id" placeholder="Tracking id">
<button id="tracking_button" class="btn">Tracking</button>
</div>
<div id="tracking_frame" hidden>
<object type="text/html" data="https://www.tracking.com/tn=" style="min-height:390px">
</object>
/div>
And this is my jquery:
<scrip>
$('#tracking_button').on('click', function(){
$('#tracking_frame').removeAttr('hidden');
});
</scrip>
Now i have two problems, when user enter something in the input and hit button then i need to do two things:
Add the input value to the url parameter "tn" at the and make a refresh to load the data.
At first without data the will be hidden so once user pressed button we need to unhide the with new loaded data
How to achive this ?
You are already toggling the hidden attribute for your div.
Add this and check if it works:
Get the data attribute from object
Get the relevant portion of URL before =
Add your new input
Set the attribute in object again.
$('#tracking_button').on('click', function(){
$('#tracking_frame').removeAttr('hidden');
let getData = $('object').attr("data");
let getDataUrl = getData.split("=");
let newUrl = getDataUrl[0] + "=" + $('#tracking_id').val();
$('object').attr('data',newUrl);
});

Jquery Autocomplete not working correctly

I'm using jquery autocomplete.In my case I have multiple autocomplete textbox and hidden field on my page.
e.g
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
<input class='myclass' type='text'> </input>
<input class='.emp_num_hidden' type='hidden'> </input>
and so on...
so when I fire change event on hidden field then it is raised multiple time
below is my code:
$(".myclass").each(function() {
var $empName= $(this);
var $empNumber = $empName.next('input:hidden');
//things to do
//Setting variable e.g url...
$empName.autocomplete(url,{
//code...
}).result(function(event,data,formatted)
{
$empNumber.val(formatted).change();
});
});
In above code $empNumber holds the hidden field which is used to store autocomplete value i.e in this case when
we select any text from autocomplete then that selected employees number will get store in hidden field.
Based on this hidden field value I want to do ajax call which will return full details of the employee based on his
employee number.
So I have written hanldler to change event of the hidden field as below.
$(.emp_num_hidden).on('change',function (
)};
here 'emp_num_hidden' is the class of the hidden field.
Please suggest how can I prevent multiple event on hidden field change.
This is done using the $(this) object. Since the change event has a target, it will only be effecting one element. The callback function is being executed on this element, this. For example:
$(".emp_num_hidden").on('change', function (e){
alert($(this).val());
});
What will happen is that an alert window will be shown when the hidden field is changed, containing the employee number from only that hidden field. You will also notices there are a few fixes to your code.
Personally, I would make use of both id and class attributes on your objects. This gives you wide scope and narrow scope to your selectors.
Example:
HTML
<input class='myclass' type='text' id='entry-txt-1' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-1' />
<input class='myclass' type='text' id='entry-txt-2' />
<input class='emp_num_hidden' type='hidden' id='hide-txt-2' />
jQuery
$(function(){
var $empName, $empNumber;
$(".myclass").each(function(key, el) {
$empName= $(el);
$empNumber = $empName.next("input[type='hidden']");
// things to do
// Setting variable e.g url...
$empName.autocomplete(url, {
//code...
}).result(function(e, d, f){
$empNumber.val(f).change();
});
});
$(".emp_num_hidden").on('change', function(e){
var empId = $(this).attr("id");
var $employeeNumberField = $("#" + empId);
// Do the needful...
});
});
Taking this a bit further, you may want to consider making use of data attributes. You may also want to look at select event for Autocomplete. Something like:
$(function(){
$(".myclass").autocomplete({
source: url,
select: function(e, ui){
$(this).val(ui.item.label);
$(this).data("emp-number", ui.item.value);
$.post("employeedata.php", { n: ui.item.value }, function(data){
$("#empData").html(data);
});
return false;
}
});
});
This assumes that url returns an array objects with label and value properties. This would add the Employee Number as a data-emp-number attribute to the field that the user was making a selection from. The label being their Employee Name, and the value being their Employee Number. You could also use this callback to show all the other employee data based on Employee Number.
A working example: https://jsfiddle.net/Twisty/zmevd0r0/

Transferring HTML element values, to other files

Let's say I have this piece of code from first.html
<input type="text" id="name">
Go to next page
How can I make it that when you go to second.html, javascript alerts the value of [name] from first.html OR the html adds an h1 tag with the value of [name] from first.html
You can use document.getElementById() function to get input and access it's value property to read what was entered there.
The onclick attribute on your anchor element will execute a custom function which will take the href property of the anchor and append the url-encoded value of the input field.
Then it will go to that new URL.
The return false ensures that built-in href event does not execute.
function link(anchor) {
var name = document.getElementById("name").value
var url = anchor.href + "?name=" + encodeURIComponent(name);
window.location.href = url;
}
<input type="text" id="name">
Go to next page
To read the passed in variable on the receiving page, use the technique described in this SO post:
How can I get query string values in JavaScript?
you could use onclick function on anchor tag.
<input type="text" id="name">
<a onclick="goToNextPage()">Go to next page</a>
<script>
function goToNextPage()
{
var value = document.getElementById('name').value;
window.location.href="second.html?name="+value;
}
</script>
Or you could use form.submit() to post the form values to request.
As HTML is only markup language, not programming language. So, you would need either php/ javascript to fetch that value on second page.
function qs(search_for) {
var query = window.location.search.substring(1);
var parms = query.split('&');
for (var i=0; i<parms.length; i++) {
var pos = parms[i].indexOf('=');
if (pos > 0 && search_for == parms[i].substring(0,pos)) {
return parms[i].substring(pos+1);;
}
}
return "";
}
and then call that function in your second page as.
<script type="text/javascript">
document.write(qs("name"));
</script>

Passing the value of a button into a text field

I'm having some trouble with getting Javascript to pass a value (which is stored in local storage) into a textfield. Ideally, I'd like for someone to be able to click the 'apply here' button on one page, have the job number stored in local storage and then have it auto-populate the job number field on my application page with the job number.
This is what I've got so far, I have a feeling that I haven't assigned things correctly.
html (on submit page)
<p>
<form id="applyjob1" action="enquire.html" method="get">
<input type="submit" id="job1" value="Apply for Job" />
</form>
</p>
html (field I'm trying to put data into)
Job Reference Number <input required="required" id="jobNo" name="jobno" type="text" /> </br />
Javascript
window.onload = function init() {
var jobID = document.getElementById("job"); /*button name */
jobID.onsubmit = passJob; /*executes passJob function */
}
function passJob(){
var jobSubmit = localstorage.jobID("1984"); /*assigns localstorage*/
if (jobSubmit != undefined){
document.getElementById("jobNo").value = localstorage.jobID;
}
I think this code would work for your fuction.
function passJob(){
localStorage.setItem("jobID", "1984");
if (localStorage.jobID != undefined) {
document.getElementById("jobNo").value = localStorage.jobID;
}
}
You are assigning the jobSubmit wrongly. To set item, use localStorage.setItem('key', value). Note the casing as it matters.
So basically you should do
var jobSubmit = localStorage.setItem(,"jobID", "1984"); // assigns jobSubmit
And I don't see any element with id="job"

User inputted query for reddit search API

Now that I can utilize the search function for reddit's API, I want the user to input their own query. I'm new to javascript and I think the problem with my code is that the API search function is being ran before the user even inputs the query.
HTML:
<div id="site-content">
<form name="RedditSearch">
Enter your query:
<input type="text" name="query" onkeydown="if (event.keyCode == 13) document.getElementById('search').click()"/>
<input type="button" id="search" value="Search" onclick="searchquery();" />
</form>
</div>
Javascript:
var container = $('#site-content')
function searchquery()
{
var query = document.RedditSearch.query.value;
}
$.getJSON("http://www.reddit.com/search.json?q=" + query, function(data) {
$.each(data.data.children, function(i,item){
var title = item.data.title
var post = '<div>'+title+'</div>'
container.append(post)
});
});
Indeed, it appears that your getJSON query is executed when the page loads. At that time, the user hasn't input anything yet, so it is executed too early.
You need to add an event listener which will detect user input, and then perform the AJAX call to the reddit API.
Assuming your user inputs his keywords in a text area, you could use .change().
You can fine more informations here : http://api.jquery.com/category/events/‎ or here http://www.w3schools.com/jquery/event_change.asp
Example in your case : http://jsfiddle.net/2ECG6/1/

Categories