Create a single search box which searches two different sites using javascript - javascript

I've made multiple search boxes that search external dictionary sites. Due to the site search syntax, I've had to use JavaScript to construct a url from the text box input. This code works perfectly fine:
function prepare_link_glosbe() {
var url_param_gl = document.getElementById('url_param_gl');
var target_link_gl = document.getElementById('target_link_gl');
if ( ! url_param_gl.value ) {
return false;
}
target_link_gl.href = "https://nb.glosbe.com/en/nb"
target_link_gl.href = target_link_gl.href + '/' + encodeURI(url_param_gl.value);
window.open(target_link_gl.href, '_blank')
}
function prepare_link_dict() {
var url_param_dict = document.getElementById('url_param_dict');
var target_link_dict = document.getElementById('target_link_dict');
if ( ! url_param_dict.value ) {
return false;
}
target_link_dict.href = "https://www.dict.com/engelsk-norsk"
target_link_dict.href = target_link_dict.href + '/' + encodeURI(url_param_dict.value);
window.open(target_link_dict.href, '_blank')
}
<!--Search Glosbe.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search glosbe.com" name="url_param_gl" id="url_param_gl" size="40"/>
<input type="button" onclick="prepare_link_glosbe()" value="Glosbe (en-no)" />
<a href="https://nb.glosbe.com/en/nb" id="target_link_gl" target="_blank" ></a>
</td></tr></table></div>
<!--Search Dict.com-->
<div style="border:0px solid black;padding:8px;width:60em;">
<table border="0" cellpadding="2">
<tr><td>
<input type="text" onfocus="this.value=''" value="Search dict.com" name="url_param_dict" id="url_param_dict" size="40"/>
<input type="button" onclick="prepare_link_dict()" value="Dict (en-no)" />
<a href="https://www.dict.com/engelsk-norsk" id="target_link_dict" target="_blank" ></a>
</td></tr></table></div>
However, I wish to search both sites using a single input box. I've tried different approaches, including addEventListener, but I'm not fluent enough in either HTML or JavaScript to achieve it. Can anyone point me in the right direction?

First of all, some things that will make your life easier in the long run:
You don't need this.value='', just use the placeholder attribute - it's well supported.
Don't use <table> to create a layout.
Don't use attributes to assign JS event handlers. (so no onclick=)
And now, how to use just one text field for both websites - just remove the second field and move the button somewhere else. Here's an example:
// This is our search input field.
const searchValue = document.getElementById('search_value');
// Here I'm looking for all search buttons and iterating over them
// with for ... of, querySelectorAll accepts valid CSS selectors.
for (let button of document.querySelectorAll('.search_button')) {
// Getting the data-url attribute value from the button.
const url = button.dataset.url;
// Adding a click event handler, instead of relying on onclick=''
button.addEventListener('click', function () {
// Quick string replace...
const targetURL = button.dataset.url.replace('%s', encodeURI(searchValue.value));
// ...and here we open the new tab.
window.open(targetURL, '_blank');
});
}
<div>
<input type="text" placeholder="Search..." id="search_value" />
<button class="search_button" data-url="https://nb.glosbe.com/en/nb/%s">Glosbe (en-no)</button>
<button class="search_button" data-url="https://www.dict.com/engelsk-norsk/%s">Dict (en-no)</button>
</div>
Here's the explanation:
I'm using the HTML data-* attributes (accessible in JS via element.dataset.*) to store the URL, %s is being used as a placeholder for the search value and will be later replaced with the .replace function.
Instead of manually assigning IDs to buttons I've declared a class - this allows you to extend the application infinitely.
I've merged the input fields into just one and read its value in the button event handler.
I've replaced your this.value='' hack with a proper placeholder.
I've removed the table layout, if you wish to add a nicer layout or styling I would suggest to learn more about CSS - also: don't use HTML attributes to style elements (except for class and style). Avoid using ID selectors in CSS as well (it's fine in JS, but in CSS it can cause issues when it comes to importance). Also, you should avoid the style attribute anyway - it will take precedence over most CSS rules except for the rules with !important and causes code duplication.

Related

jQuery Clone() not behaving as it should within asp.net page

I have a search box that needs to be within a form so that it can post to another page for a search functionality to work.
I originally had this working fine in Firefox by using an iFrame, but using the search box would simply refresh the when using Internet Explorer.
I found out that it worked fine if I simply created another form underneath the current one, however this obviously leaves it in the wrong place on the page.
I attempted to use the jQuery clone() method that I have succesfully used elsewhere on the site, but this is refusing to work.
I looked around and found another way of using the clone() method and I have it working fine within jsfiddle, but it will not work on my site.
This is the div that I want to populate:
<div id="CustomerSearch">
2
</div>
And this is the div that I want to be cloned:
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">
1
Customer Search: <br />
<input type="text"id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
This is the script that I am using in an external file:
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
CustomerSearch.html(CustomerSearchClone.clone(true));
I have it working in JSFiddle here: http://jsfiddle.net/de9kc/92/
Any ideas?
Thanks guys
I'm not a .NET guy but the div you are pasting too is still within a form tag so I'm not certain that this wouldn't cause a hiccup for .NET at submission time (or postback, or whatever).
However, with respect to getting the cloned form elements where you wanted them per the layout you demonstrate in your question;
I modified the pre-result html like so:
//html
<form id="form1" runat="server">
<div id="CustomerSearch">2 Customer Search:</div>
</form>
<form name="frmCustomerList" action="../CustomerList/default.asp" method="post">
<div id="CustomerSearchClone">1 Customer Search:
<br />
<input type="text" id="txtSearch" name="txtSearch" class="Searchbox" />
<input type="submit" value="View" name="txtSearchSubmit" />
</div>
</form>
then i used this jQuery:
// the vars you already created
var CustomerSearch = jQuery('#CustomerSearch');
var CustomerSearchClone = jQuery('#CustomerSearchClone');
// using .clone(true, true) for deepWithDataAndEvents - not sure if you want this?
// will the .clone(true, true) retain input's link to original form id? I'm uncertain
// using .children() because clone's intended destination already has a div container
CustomerSearchClone.children().clone(true, true).appendTo(CustomerSearch);
// hide clone's source after cloning; no sense in having both search boxes visible
CustomerSearchClone.hide();
Note: Using .clone() has the side-effect of producing elements with duplicate id attributes, which are supposed to be unique. (per http://api.jquery.com/clone/)
But you are appending the cloned elements into a different form tag, so maybe a non-issue.
I'm just learning jQuery myself, but I thought I would give the solution a shot ;-$
JSFiddle here: http://jsfiddle.net/de9kc/190/

JQuery: Append/After difficulties

I have a simple input line and want to append whatever has been entered each time somebody pushes the OK button. Sounds simple so far, still I am unable to get it working
HTML:
<p>
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<p id="status">Ok</p>
<br>
JQuery:
$(document).ready(function(){
$('#status').on('click', function(){
var input = $('input[name=todo]').val();
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').after('#status');
});
});
I also tried my luck with append or appendTo, but both times unsuccessfully.
Just in case here is the JSFiddle: http://jsfiddle.net/NRWzE/
.after() works, but you need to set it up correctly, according to documentation it should be:
.after( content [, content ] )
So the right way is:
$("#status").after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
Try use jquery insertAfter:
$(document).ready(function () {
$('#status').on('click', function () {
var input = $('input[name=todo]').val();
$('<br><b id="taskz">' + input + '</b> - <b id="statusz">Ok</b>').insertAfter('#status');
});
});
It looks like you meant to use:
$('#status').after('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
(see after docs)
or, alternatively insertAfter:
$('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>').insertAfter('#status');
Try this:
$('#status').click(function(){
var input = $('input[name=todo]').val();
$('#status').append('<br><b id="taskz">'+input+'</b> - <b id="statusz">Ok</b>');
});
There are a few things going on, but the big thing is that you need to research more how after, append and appendTo work. Here's the basic syntax difference in the methods that share a name but one has To on the end:
Newcontent.appendTo(existingElement) returns newElements.
existingElement.append(newContent) returns existingElement.
Additionally, after puts the new element as a sibling of the reference element, whereas append puts the new element as a child. This is an important difference.
So, try this script then:
var taskid = 1;
$('#valueform').on('submit', function(){
var input = $('#todo').val();
$('<br><span id="task' + taskid.toString() + '">' + input
+ '</span> - <span id="status' + taskid.toString()
+ '">Ok</span>').appendTo('#status');
taskid += 1;
$('#todo').focus().select();
return false;
});
$('#todo').focus().select();
See a Live Demo at JSFiddle
Here's the supporting HTML:
<form id="valueform">
<input name="todo" id="todo" type="text" value="Set Me To Value" size="32" maxlength="30" />
<input type="submit" value="OK" id="okbutton">
</form>
<p id="status"></p>
There are some other concerns:
I recommend you study which HTML elements are allowed within which HTML elements.
Instead of putting a <b> tag on each item, use CSS. Additionally, if there is semantic importance for the bolding, then use <strong> instead. <b> also should probably not take an id because it is a presentation tag, not a content tag. When thinking of presentation vs. semantics, one must consider screen readers or browsers that cannot render bold text--in that case, <strong> will allow them to emphasize the text in another way if needed.
Get familiar with the jQuery documentation. Careful reading of what exactly each function does, the object it works on, the parameters expected, and the values returned will enable you to get past barriers in the future without having to ask here.
It looked to me like you wanted to put the new content inside of the #status paragraph, not after it. So I wrote my script that way. If you put it after the way you wrote it, then the most recent status will be on top--but then you have non block-level content (starting with your <br>) outside of any block-level element. So you should be appending <p> elements, or you should put your content inside the existing <p>.
Note: I added a form and made the button type submit instead of button to get easy Enter-key handling. It doesn't have to be this way.

How to make the input have text in it while on focus?

Please check the link below:
http://jsfiddle.net/cT9kg/4/
As you can see its a search field with a button.
If you have trouble understanding what I mean below please just look at the "Title" input on the Ask a question page.
The input has autofocus on.
BUT
How can I have it so text is already in the input with autofocus on but as soon as someone types into the input the text disappears.
AND
When someone has entered text in the input but then deletes it, it goes back to the way it was at the beginning: on focus with text in it instructing the person what to type in the input.
Thanks!
James
You could define the default value.
On focus - empty value, if the value is default value.
When the element lose the focus, You could check, if it's empty, and if Yes - restore the default value.
I've tested this as working, just make sure you put the <script> part just before the </body> tag.
<input type="text" class="input1" autofocus="focus" id="search" value="Type here..." onKeyPress="checkValue()" />
----
<script type="text/javascript">
var searchEl = document.getElementById('search');
var defaultValue = searchEl.value;
function checkValue() {
if (searchEl.value == defaultValue) {
searchEl.value = "";
}
}
</script>
You could use the HTML placeholder attribute, but in the majority of browsers that won't achieve quite what you are after: as soon as the input is focused, the placeholder text disappears.
For functionality akin to iOS (found on sites such as Twitter as well), you need to use JavaScript. One example can be seen online here.
This similar question (and this one) have some useful alternatives and code examples.
You're correctly using autofocus, which is fine but has patchy browser support. You can add in a JS fallback, like this (taken from here):
<script>
window.onload = function () {
if (!("autofocus" in document.createElement("input"))) {
document.getElementById("s").focus();
}
}
</script>
Wow. I tried digging around in the source code for the Ask a question page. Talk about convoluted.
Here is the CSS File.
While it seems the relevant bits are thus, they don't seem to DO much more than format (other than the edit-field-overlay trick.
.form-item {padding:10px 0px 15px 0px;}
.ask-title {margin-bottom:-15px;margin-top:-10px;}
.ask-title-table {width:668px;}
.ask-title-field {width:610px;}
.ask-title-cell-value {padding-left:5px;}
.edit-field-overlay {display:none;}
HTML (some TD tags removed):
<div class="form-item ask-title">
<table class="ask-title-table">
<tr>
<td class="ask-title-cell-value">
<input id="title" name="title" type="text" maxlength="300" tabindex="100" class="ask-title-field" value="">
<span class="edit-field-overlay">what's your programming question? be specific.</span>
</td>
</tr>
</table>
</div>
But I totally could NOT figure out the relevant Javascript bits. As there are NO onEvent handlers for this form that I can see, the only reference to this field (title) would be in the prepareEditor function.
Anybody care to try and explain it to a relative newbie??

How can you logically group HTML elements without taking the help of CSS classes?

I know that in jQuery you can use something like $(".cssClass") to get all elements with this class. However in plain html and javascript how do you group elements logically? For example:
<input id="fee1" data-id="1" data-group="Fees" type="text" value="$15.00"/>
<input id="fee2" data-id="2" data-group="Fees" type="text" value="$25.00"/>
<input id="fee3" data-id="3" data-group="Fees" type="text" value="$35.00"/>
I want to create a javascript function like this:
function GetByDataGroup(dataGroup){
/* returns something like [[1,"$15.00"],[2,"$25.00"],[3,"$35.00"]]*/
}
EDIT : Due to some political reasons I cant use jQuery or any framework..i know it doesnt make sense :)
In the case of form elements like you've given in your example, the <fieldset> is the logical grouper.
Your form can (and some might go as far as to say 'should') have many fieldsets breaking up your form into logical areas.
Once you have the relevant form fields divided up into the logical <fieldset>'s you can grab these using your Javascript either through a class/id on the fieldset, or some other selector (perhaps you're grabbing all fieldsets on the page etc).
This makes it a lot easier if you're using Plain Old Javascript rather than a framework to grab those items by some kind of id. Consider:
<fieldset id="contactDetails">
<input ... />
<input ... />
<input ... />
</fieldset>
Using your POJ you can get all of these from:
var contactDetails = document.getElementById('contactDetails');
Can you use another javascript framework? There are many: http://en.wikipedia.org/wiki/Comparison_of_JavaScript_frameworks
You could use something like this:
function getElementsByClass(node,searchClass,tag) {
var classElements = new Array();
var els = node.getElementsByTagName(tag); // use "*" for all elements
var pattern = new RegExp('\\b'+searchClass+'\\b');
for (var i = 0; i < els.length; i++)
if ( pattern.test(els[i].className) )
classElements[classElements.length] = els[i];
return classElements;
}
(from here: http://www.dynamicdrive.com/forums/showthread.php?t=19294)

How can I create a dynamic form using jQuery

How can I create a dynamic form using jQuery. For example if I have to repeat a block of html for 3 times and show them one by one and also how can I fetch the value of this dynamic form value.
<div>
<div>Name: <input type="text" id="name"></div>
<div>Address: <input type="text" id="address"></div>
</div>
To insert that HTML into a form 3 times, you could simply perform it in a loop.
HTML:
<form id="myForm"></form>
jQuery:
$(function() {
var $form = $('#myForm'); // Grab a reference to the form
// Append your HTML, updating the ID attributes to keep HTML valid
for(var i = 1; i <= 3; i++) {
$form.append('<div><div>Name: <input type="text" id="name' + i + '"></div><div>Address: <input type="text" id="address' + i + '"></div></div>')
}
});
As far as fetching values, how you go about it would depend on your intent. jQuery can serialize the entire form, or you can select individual input values.
.append() - http://api.jquery.com/append/
This is a pretty broad question and feels a lot like 'do my work' as opposed to 'help me solve this problem.' That being said, a generic question begets an generic answer.
You can add new address rows by using the append() method and bind that to either the current row's blur - although that seems messy, or a set of +/- buttons that allow you to add and remove rows from your form. If you're processing the form with PHP on the server side, you can name the fields like this:
<input type='text' name='address[]' />
and php will create an array in $_POST['address'] containing all the values.

Categories

Resources