Passing a Query from one Domain to another using JavaScript - javascript

I need to be able to create a query based off the users input of "Test" in an INPUT of Site A (SiteA.com) that will open Site B in the same window once submitted, passing along the query (SiteB.com/search.aspx?k=test).
Code on SiteA.com
var siteSearch = "SiteB.com/search.aspx";
$("#sitesubmitBtn").click(submitClick);
function submitClick() {
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
var k = $("#sitesearchInput").val();
window.location.href = q + "?k=" + k;
return false;
}
<input name="search" placeholder="Search" id="sitesearchInput" type="text">
<button id="sitesubmitBtn" type="submit"></button>

You are describing a simple HTML form. You don't need JavaScript/jQuery for that to happen.
<form method="GET" action="//SiteB.com/search.aspx">
<input type="text" name="k" placeholder="Search term" />
<button type="submit">Search</button>
</form>

change this line
var q = $(location).attr('protocol') + "//" + $(location).attr('hostname') + siteSearch;
to :
var q = $(location).attr('protocol') + "//" + siteSearch;
because you already define your hostname in this line:
var siteSearch = "SiteB.com/search.aspx";

Related

return string in javascript

I want to get apiUrl depending on a user's input
<form name="test">
<input type="text" name="Edit">
<input type="button" value="Test" onClick="gettext()">
<input type="text" name="Edit2" readonly style="border:1px solid white">
</form>
Then i have a script which does not work, to form a url based on that
<script>
function gettext(Edit, Edit2) {
document.test.Edit2.value=document.test.Edit.value;};
var apiKey = '07gh4c95ca7e23d41ghggf/';
var userWord = Edit2;
var txtjson = '/json';
var apiUrl = 'http://words.bighugelabs.com/api/2/' + apiKey + userWord + txtjson;
</script>
I need var userWord to be a string to insert its value in the apiUrl.
Please help me with that. Thank you
Edit2 is not declared outside the gettext function. Try this:
function gettext(Edit, Edit2) {
document.test.Edit2.value = document.test.Edit.value;
return document.test.Edit2.value;
}
var userWord = gettext(<param1>, <param2>);

Stop form from sending and execute a function

This is my form:
<form id="search_form" method="get" action="" name="search_f">
<input id="search_field" maxlength="100" name="query" type="text" value="" placeholder="cerca nel negozio">
<input id="search_button" type="submit" value="" onClick="submit_f()">
</form>
This is "submit_f()":
function submit_f(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}
What I'm trying to do is to redirect the user to different pages based on what he enters:
- If he enters words he'll be redirected to "/search/?query=words".
- IF he enters an url (http://store.steampowered.com/app/202170/?asp=123) he'll be redirected (in this case) to "/app/202170".
But my code isn't working, any help?
You aren't returning anything from your event handler function:
onClick="submit_f()"
should be
onClick="return submit_f()"
You should give your form a
onsubmit="return false"
to avoid the default submitting behaviour. Also, your button could be type=button instead of type=submit, but that's not always enough (some browsers will still submit it), the sure way is onsubmit.
remove the onclick from your html
document.getElementById('search_button').onclick = function(){
var v = document.search_f.query.value;
var v_arr = v.split("?");
alert(v_arr.join('\n'));
var v_arr = v_arr[0].split("/");
alert(v_arr.join('\n'));
if((v_arr[0] == "http:" || v_arr[0] == "https:") && v_arr[2] == "store.steampowered.com")
window.location.href = "/" + v_arr[3] + "/" + v_arr[4];
else
window.location.href = "/search/?query=" + v;
return false;
}

Generating JSON String from Form

I am new to JSON and trying hard to understand it's working.
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID">
<button type="submit" class="btn btn-success" >Submit Data</button>
</form>
JSON String to be generated as:
{"latency":1.6,"throughput":6.01,"outUID":{"V_ID":"40"},"inUID":{"V_ID":"16"}}
Here's the form and JSON String to be generated
Could some one guide me how do I create that nested JSON object?
Since it looks like you want the values of outUID and inUID to be nested for some reason you'll need to build the object manually. Here's a simple example:
var $latency = $('#latency'),
$throughput = $('#throughput'),
$outUID = $('#outUID'),
$inUID = $('#inUID');
var myJSONObject = {
latency:$latency.val(),
throughput:$throughput.val(),
outUID:{
V_ID:$outUID.val()
},
inUID:{
V_ID:$inUID.val()
}
};
var stringJSON = JSON.stringify(myJSONObject);
Pure javascript example
var els=document.getElemtById('edge').getElementsByTagName('input');
or
var els=document.querySelectorAll('input[class=input-"xlarge"]');
to get the elements
then
var array=[]
for(var a=0,b;b=els[a]; ++a){
array[a]=b.value
}
array is the json object
JSON.styringify(array)
is the json string
tip: if you plan to use this with ajax
there is a new way called FormData();
so:
var fd=FormData(document.getElemtById('edge'));
contains the whole form , including files
This code allow you to add more fields if required to do so without hard coding the field attributes
http://jsfiddle.net/6vQY9/
HTML
<form id="edge" class="form-horizontal" method="post" action="javascript:submit();">
<input type="text" class="input-xlarge" id="latency" name="latency" placeholder="latency">
<input type="text" class="input-xlarge" id="throughput" name="throughput" placeholder="throughput">
<input type="text" class="input-xlarge" id="outUID" name="outUID" placeholder="outUID" data-prop="V_ID">
<input type="text" class="input-xlarge" id="inUID" name="inUID" placeholder="inUID" data-prop="V_ID">
<button type="submit" class="btn btn-success">Submit Data</button>
</form> <pre></pre>
JS
function submit() {
var JSONString = "";
jQuery('#edge input').each(function () {
var that = jQuery(this);
var val = that.val();
var partJSON = "";
var quote = "\"";
if (that.data('prop')) {
partJSON = "{ " + quote +that.data('prop') + quote+ " : " + quote + val + quote + " }";
} else {
partJSON = val;
}
var comma = that.next('input').length > 0 ? "," : "";
partJSON = quote + that.prop('id') + quote + ":" + partJSON + comma;
JSONString += partJSON
});
JSONString = "{ " + JSONString + " }";
jQuery('pre').text(JSONString);
}

Form Hidden Field Substitution

I'm building a form using Expression Engine's Safecracker module.
One of the the required fields is the Title, which becomes the title of the EE channel entry.
What I'd like to do is set the Title field to be the combined first name and last name fields.
I started with this:
<form method="POST" action="#">
<input id="student_first_name" type="text" size="30" name="student_first_name">
<br>
<input id="student_last_name" type="text" size="30" name="student_last_name">
<br><br>
<input type="text" name="title" value=""/>
</form>
And then added this:
$(function() {
$('#student_first_name').keyup(function() {
var snamef = $(this);
});
$('#student_last_name').keyup(function() {
var snamel = $(this);
});
$("input[name='title']").val(snamel + " " + snamef);
return false;
});​
​I can't get it to work, though: http://jsfiddle.net/tylonius/CY5zJ/4/
Am I missing a step (or just totally doing it wrong?)?
Also, am I possibly working too hard and Safecracker already has this function built in; similar to its live UrlTitle(); function?
Any help is appreciated.
Thanks,
ty
If I understood right your question try this:
First set an id on your desired input element, like this :
<input type="text" name="title" id="student_title" value=""/>
And then :
$(function() {
changeFunction = function() {
$('#student_title').val($('#student_first_name').val() + ' ' + $("#student_last_name").val());
}
$('#student_first_name').keyup(changeFunction)
$('#student_last_name').keyup(changeFunction);
});
Better yet, avoid using javascript altogether and just use SafeCracker's dynamic_title parameter.
dynamic_title="[student_first_name] [student_last_name]"
user1236048 has the best solution for you but below is a working version of your code
$(function() {
var snamef;
var snamel;
$('#student_first_name').keyup(function() {
snamef = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
$('#student_last_name').keyup(function() {
snamel = $(this).val();
$("input[name='title']").val(snamel + " " + snamef);
});
return false;
});
and here is the working jsfiddle

What's the best way to update the input names when dynamically adding them to a form?

I'm trynig to come up with a clean and efficient way of handling form input names when dynamically adding more to the POST array.
For example, if I have the following form:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I then click an 'addmore' button which duplicates that HTML and adds it back into the document. Resulting in:
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
I'm trying to find the best way to increment that name index so I can use the data on the server. So far, I've been using the following code:
$('.addmore').click(function()
{
var $button = $(this);
var $fieldset = $button.prev('fieldset');
var $newset = $('<div class="new">' + $fieldset[0].innerHTML + '</div>');
$newset.insertBefore($button);
updatenames($newset, $('fieldset').length + 1);
});
function updatenames($set, newIndex)
{
/*
updates input names in the form of
set-index.name
set-index
*/
var findnametype = function(inputname)
{
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') != -1)
{
var data1 = inputname.split('-');
var data2 = data1[1].split('.');
// [type, set, index]
return [1, data1[0], parseInt(data2[0])]
}
if (inputname.indexOf('-') != -1 && inputname.indexOf('.') == -1)
{
var data = inputname.split('-');
return [2, data[0], data[1]];
}
return false;
};
var type = findnametype($set.find('input:eq(0)')[0].name);
$set.find('input, select').each(function()
{
var $input = $(this);
var oldname = $input[0].name;
var newname = false;
switch (type[0])
{
case 1: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
case 2: newname = oldname.replace('-' + type[2], '-' + newIndex);
break;
}
$input[0].name = newname;
});
return type;
}
That updatenames function is a variation of what I've been using lately. In this case, I check to find the format of the input name. I then increment the index.
The incrementing, as you've probably noticed, happens in the DOM. As a 'part 2' to my question, I'd like to learn how to have that object returned for me to then insert into the DOM.
Something like:
$newset = updatenames($newset, $('fieldset').length +1);
$newset.insertBefore($button);
Your help is appreciated. Cheers.
Have you considered using array-based field names? You wouldn't have to alter those at all:
<input type="text" name="users.firstname[]" />
<input type="text" name="users.lastname[]" />
whether this works for you will of course depend on what you're going to do with the fields.
<script type="text/javascript">
$(document).ready(function () {
$('.addmore').click(function () {
var fieldset = $(this).prev('fieldset');
var newFieldset = fieldset.clone();
incrementFieldset(newFieldset);
newFieldset.insertBefore($(this));
});
});
function incrementFieldset(set) {
$(set).find('input').each(function () {
var oldName = $(this).attr('name');
var regex = /^(.*)-([0-9]+)\.(.*)$/;
var match = regex.exec(oldName);
var newName = match[1] + '-' + (parseInt(match[2]) + 1) + '.' + match[3];
$(this).attr('name', newName);
});
}
</script>
<fieldset>
<input type="text" name="users-0.firstname" />
<input type="text" name="users-0.lastname" />
</fieldset>
<input type="button" class="addmore" value="Add" />
<fieldset>
<input index=1 var=user prop=firstname />
<input index=1 var=user prop=lastname />
</fieldset>
<fieldset>
<input index=2 var=user prop=firstname />
<input index=2 var=user prop=lastname />
</fieldset>
before you submit your form
get the custom attributes and construct your 'name' attribute
[update]
its jsp but shouldn't be hard for u to convert to php
<%
for (int i = 0; i < 1000; i++) {
%>
<fieldset>
<input index=<%=i%> var=user prop=firstname />
<input index=<%=i%> var=user prop=lastname />
</fieldset>
<%
}
%>
for the js code
$('button').click(function(){
$('input').each(function(i, node){
var $node = $(node);
$node.attr('name', $node.attr('var') + $node.attr('index') + "."+ $node.attr('prop'))
});
});

Categories

Resources