Getting value from search box in javascript - javascript

How do I get a value from search box in javascript?
I'd like to redirect users to particular pages based on what they select in the search box.
For example, if the user selected "New York" and then clicked on Yes, he'll be redirected to page /about/New York
This work for static pages, but for some reasons I can't get the value from the search box.
In Ruby I woud get it with params[:query_name]
I am using hidden_value and tag 'search'
var val = getElementsByTagName('search').value;
if (r) {
location.href = "/about/" + val";
}

You may also need to specify this == document and use double quotes in case 'search' is a reference to an object, to make sure it is properly interpolated
var val = document.getElementById("search").value;
or with jQuery:
var val = $("#search").val();

Did you mean (since I dont think there is an html tag named search):
var val = getElementById('search').value;
if (r) {
window.location.href = "/about/" + val;
}
So above code assumes your element has id set like id="search"
By the way, to select an specific element using getElementsByTagName, you also need to specify index since it returns Node list:
getElementsByTagName('tagName')[indexHERE].value

getElementsByTagName returns an array of many objects based on the tag name, e.g. input,div,a etc. If this is what your search bar looks like:
<input id="search" />
Then do:
getElementById('search').value;

Related

Create one tag according to given info on button click

I have this form on my website:
<form action>
<input type = "number" placeholder = "Combat ID" name = "combat id" min = "0" max = "9999999999" required/>
<button type = "button" id = "check_button">Check</button>
<div class = "form-group">
<label for = "Character" style = "color:white;">Character</label>
<select id = "Character" name = "Character">
List of chars
</select>
</div>
<h2 style = "color:white;padding-top:2%;">Other info</h2>
...............
<button type = "submit" class = "btn btn-default">Submit!</button>
</form>
What I want is when you enter combat id you click the button "Check" then in select box it shows only these 5 characters that were in that combat.I get these 5 character names from API,when submitting combat id to API.
So when a user clicks the button "Check" I need to send request to API with given combat id and then accordingly fill the select tag.
I am not gonna spoon feed you and tell you everything, but I will give you a good head start.
Since you've allowed jQuery, here is how I'd do it:
jQuery code:
<input id="combat-id" type = "number" placeholder = "Combat ID" name = "combat id" min = "0" max = "9999999999" required/>
Basically, I gave the Combat ID field an id of combat-id
Now, on this JS code, what you do is, you call the $() function in the jQuery library, and pass it a selector #check_button and you add an event listener to it. You call the on function on the selector, and give it the action in string for the first argument, and in the second argument, you pass a closure to be executed when this event happens.
On the first line, you get the value in the #combat-id field.
$('#check_button').on('click', function (event) {
var combatId = $('#combat-id').val();
// Do what you want with it now.
event.preventDefault();
});
The event.preventDefault(); is called to stop the page from refreshing. The closure in the second argument is passed an event variable which can be used to do various things in the event.
So now, you only have to call the API now and populate the list. You can do it very easily.
If you wanna do a POST request, do this:
$.post('/url/to/go', { var: val, combatId: combatId });
Or for a GET request:
$.get('/url/to/go', { var: val, combatId: combatId });
Since you are using PHP, you can get the combatId like this:
$_GET['combatId'] or $_POST['combatId'] depending on the REQUEST method you chose.
You can assign each request to a variable like this:
var request = $.post(....);
And do something like:
request.success( function (data) {
// the data variable will have data you displayed to the screen.
});
request.error( function (error) {
// this will be called if the request failed. The error variable will have some sort of error info.
});
So in this code, you can put some code in the .success() function to populate the list. What you can do is output content using PHP in the JSON format, and you can parse it in JavaScript like this:
data = JSON.parse(data)
What this will do is, it will convert the JSON (JavaScript Object Notation, a language to represent JS like objects, which is a String in JavaScript) to native a JavaScript Object.
To append, give the <select> tag an id, lets say #select
Then, you can select it and add strings to it like this:
$('#select').append('<option value="' + data.value + '">' + data.text + '</option>');
In here, I assume data is an object with two properties: value and text and I append that data into the <select> list.

changing the value of a select box by only having the xpath

I am currently using robotium to record a load of actions in an android web view. There is a known bug in robotium that doesnt let you change the value of a select box. in order to combat this when the test is running i am creating another javascript injection to change it. It works with name and Id but it needs to be able to use xpath as well in case a name or id arent available.
At the moment I can do this using the name and Id of the select box using:
selectBox = document.getElementById(identifyingValue);
or
selectBox = document.getElementByName(identifyingValue);
After this I can create a method to change the value of the select box the value that I want. The issue is that sometimes i cannot get the id or name of the select box and there isn't a similar method to do this via an Xpath ie:
selectBox = document.getElementByXpath(identifyingValue);
My code currently looks like this:
var selectBox;
var identifyingAttribute = ('$identifyingAttribute');
var identifyingValue = ('$identifyingValue');
var selectedIndex = '$selectedIndex';
if (identifyingAttribute === 'id') {
selectBox = document.getElementById(identifyingValue);
} else if (identifyingAttribute === 'name') {
selectBox = document.getElementByName(identifyingValue);
} else if (identifyingAttribute === 'xpath') {
selectBox = document.getElementByXpath(identifyingValue);
}
selectBox.selectedIndex = selectedIndex;
if (selectBox.onchange) {
selectBox.onchange();
}
So far you can see that I am trying to use the id and name first and the xpath as a last resort.
Is they a away that I can select an element by its Xpath and then change its value or perform a similar action. Any help or input would be greatly appreciated.
you can use document.querySelector() and select the property with a css selector.
documentation can be found here: https://developer.mozilla.org/en-US/docs/Web/API/document.querySelector
I have found a solution to the problem using document.evaluate()
The statement works for me:
selectBox = document.evaluate(identifyingValue, document, null , 9, null).singleNodeValue;

jQuery navigating XML parent child nodes and selecting appropriate attributes from each?

I am creating a templating system which can be interpreted at client side with Javascript to construct a fill in the blanks form e.g. for a letter to a customer etc.
I have the template constructed and the logic set out in pseudo code, however my unfamiliarity with jQuery I could use some direction to get me started.
The basic idea is there is a markup in my text node that denotes a field e.g. ${prologue} this is then added to an array called "fields" which will then be used to search for corresponding node names in the xml.
XML
<?xml version="1.0" encoding="UTF-8"?>
<message>
<text>${Prologue} - Dear ${Title} ${Surname}. This is a message from FUBAR. An engineer called but was unable to gain access, a new appointment has been made for ${ProductName} with order number ${VOLNumber}, on ${AppointmentDate} between ${AppointmentSlot}.
Please ensure you are available at your premises for the engineer. If this is not convenient, go to fubar.com or call 124125121515 before 12:00 noon the day before your appointment. Please refer to your order confirmation for details on what will happen on the day. ${Epilogue} - Free text field for advisor input<
</text>
<inputTypes>
<textBox type="text" fixed="n" size="100" alt="Enter a value">
<Prologue size="200" value="BT ENG Appt Reschedule 254159" alt="Prologue field"></Prologue>
<Surname value="Hoskins"></Surname>
<ProductName value=""></ProductName>
<VOLNumber size="8" value="" ></VOLNumber>
<Epilogue value=""></Epilogue>
</textBox>
<date type="datePicker" fixed="n" size="8" alt="Select a suitable appointment date">
<AppointmentDate></AppointmentDate>
</date>
<select type="select" >
<Title alt="Select the customers title">
<values>
<Mr selected="true">Mr</Mr>
<Miss>Miss</Miss>
<Mrs>Mrs</Mrs>
<Dr>Dr</Dr>
<Sir>Sir</Sir>
</values>
</Title>
<AppointmentSlot alt="Select the appointment slot">
<values>
<Morning>9:30am - 12:00pm</Morning>
<Afternoon>1:00pm - 5:00pm</Afternoon>
<Evening>6:00pm - 9:00pm</Evening>
</values>
</AppointmentSlot>
</select>
</inputTypes>
</message>
Pseudocode
Get list of tags from text node and build array called "fields"
For each item in "fields" array:
Find node in xml that equals array item's name
Get attributes of that node
Jump to parent node
Get attributes of parent node
If attributes of parent node != child node then ignore
Else add the parent attributes to the result
Build html for field using all the data gathered from above
Addendums
Is this logic ok, is it possible to start at the parent of the node and navigate downwards instead?
Also with regards to inheritence could we get the parent attributes and if the child attributes are different then add them to the result? What about if the number of attributes in the parent does not equal the number in the child?
Please do not provide fully coded solutions, just a little teasers to get me started.
Here is what I have so far which is extracting the tags from text node
//get value of node "text" in xml
var start = $(xml).find("text").text().indexOf('$');
var end = $(xml).find("text").text().indexOf('}');
var tag = "";
var inputType;
// find all tags and add them to a tag array
while (start >= 0)
{
//console.log("Reach In Loop " + start)
tag = theLetter.slice(start + 2, end);
tagArray.push(tag);
tagReplaceArray.push(theLetter.slice(start, end + 1));
start = theLetter.indexOf('$', start + 1);
end = theLetter.indexOf('}', end + 1);
}
Any other recommendations or links to similar problems would be welcome.
Thankyou!
I am using a similar technique to do html templating.
Instead of working with elements, I find it easier to work with a string and then convert it to html. In your case with jQuery, you could do something similar:
Have your xml as a string:
var xmlString='<?xml version="1.0" encoding="UTF-8"?><message><text>${Prologue} - Dear ${Title} ${Surname}... ';
Iterate through the string to do the replacements with a regex ($1 is the captured placeholder, for example Surname):
xmlString.replace(/$\{([^}]+)}/g,function($0,$1)...}
Convert to nodes if needed:
var xml=$(xmlString);
The benefits of the regex:
faster (just a string, you're not walking the DOM)
global replace (for example if Surname appears several times), just loop through your object properties once
simple regex /${([^}]+)}/ to target the placeholder
Get list of tags from text node and build array called "fields"
To create the array I would rather user regular expression, this is one of the best use for it (in my opinion) because we are indeed searching for a pattern :
var reg = /\$\{(\w+)\}/gm;
var i = 0;
var fields = new Array();
while ( (m = reg.exec(txt)) !== null)
{
fields[i++] = m[1];
}
For each item in "fields" array
jQuery offers some utility functions :
To iterate through your fields you could do this : $.each(fields, function(index, value){});
Navigating through the nodes and retrieving the values
Just use the jQuery function like you are already doing.
Building the HTML
I would create templates objects for each types you would take in charge (in this example : Text, Select)
Then using said templates you could replace the tokens with the HTML of your templates.
Displaying the HTML
Last step would be to parse the result string and append it at the right place:
var ResultForm = $.parseHTML(txt);
$("#DisplayDiv").append(ResultForm);
Conclusion
Like you asked, I did not prepare anything that works right out of the box, I hope it will help you prepare your own answer. (And then I hope you will share it with the community)
This is just a framework to get you going, like you asked.
first concept is using a regex to just find all matches of ${ }. it returns an array like ["${one}","${t w 0 }","${ three}"].
second concept is a htmlGenerator json object mapping "inputTypes-->childname" to a function responsible for the html print out.
third is not to forget about natural javascript. .localname will give you the xml element's name, and node.attributes should give you a namedNodeMap back (remember not to perform natural javascript against the jquery object, make sure you're referencing the node element jQuery found for you).
the actual flow is simple.
find all the '${}'tokens and store the result in an array.
find all the tokens in the xml document and using their parents info, store the html in an map of {"${one}":"<input type='text' .../>","${two}":"<select><option value='hello'>world!</option></select>" ...}
iterate through the map and replace every token in the source text with the html you want.
javascript
var $xmlDoc = $(xml); //store the xml document
var tokenSource =$xmlDoc.find("message text").text();
var tokenizer=/${[^}]+/g; //used to find replacement locations
var htmlGenerators = {
"textBox":function(name,$elementParent){
//default javascript .attributes returns a namedNodeMap, I think jquery can handle it, otherwise parse the .attributes return into an array or json obj first.
var parentAttributes = ($elementParent[0] && $elementParent.attributes)?$elementParent.attributes:null;
//this may be not enough null check work, but you get the idea
var specificAttributes =$elementParent.find(name)[0].attributes;
var combinedAttributes = {};
if(parentAttributes && specificAttributes){
//extend or overwrite the contents of the first obj with contents from 2nd, then 3rd, ... then nth [$.extend()](http://api.jquery.com/jQuery.extend/)
$.extend(combinedAttributes,parentAttributes,specificAttributes);
}
return $("<input>",combinedAttributes);
},
"date":function(name,$elementParent){
//whatever you want to do for a 'date' text input
},
"select":function(name,$elementParent){
//put in a default select box implementation, obviously you'll need to copy options attributes too in addition to their value / visible value.
}
};
var html={};
var tokens = tokenSource.match(tokenizer); //pull out each ${elementKey}
for(index in tokens){
var elementKey = tokens[index].replace("${","").replace("}"),"");//chomp${,}
var $elementParent = $xmlDoc.find(elementKey).parent();//we need parent attributes. javascript .localname should have the element name of your xml node, in this case "textBox","date" or "select". might need a [0].localname....
var elementFunction = ($elementParent.localname)?htmlGenerators[elementParent.localname]:null; //lookup the html generator function
if(elementFunction != null){ //make sure we found one
html[tokens[index]] = elementFunction(elementKey,elementParent);//store the result
}
}
for(index in html){
//for every html result, replace it's token
tokenSource = tokenSource.replace(index,html[index]);
}

getting selected values from an array of select box in to javascript

I have created dynamic select box using jquery. I have created the select box as an array name=Child[]. See my code
for(i=1;i<=val;i++){
var newParagraph = $('<dl class="thirty fl"><dt>Child '+i+'</dt> <dd><select name="child[]"><option value="">--select--</option><option value="1">1</option><option value="2">2</option><option value="3">3</option</select></dd></dl>');
$('#childDynamic').append(newParagraph);
}
In form validation section (in javascript), how I validate this select box? I don't know how to get the values from an array of select box using JavaScript
Anyone can help me?
Thanks in advance
(You don't actually have an array of select elements, given that html doesn't have arrays. But anyway...)
If you use the name attribute as the selector you can get a jQuery object containing the select elements:
$('#childDynamic select[name="child\\[\\]"]')
...which you can then process as you see fit.
Because square brackets have special meaning in jQuery selectors they need to be escaped with backslashes, and to include backslashes in a string literal they need to be escaped too.
Anyway, I don't know what kind of validation you want to apply, but if you wanted to loop through each select and check its value in some way you could do something like this:
var valid = true;
$('#childDynamic select[name="child\\[\\]"]').each(function() {
var val = $(this).val();
// example validation: make sure something other than the default
// blank value is selected
if (val === "") {
valid = false;
}
});
if (!valid) {
// do something
}

How do we change the name of a html select element using javascript and only the tags' name to reference to?

HI! I have a problem with changing the name of a select element. I have about 28 select elements generated on the page. Each of these select elements has been given the name "dropdown". I use this name to calculate the total based on the option selected.
But when i pass this information to a php page, it shows only the last select element. To overcome this i need to have all the select tags labelled as "dropdown[]" onsubmit. This is because i need "dropdown" for javascript to read it and i need "dropdown[]" for php to process it.
<select name="dropdown">
<option>
<option>
<option>
</select>
should be changed to :
<select name="dropdown[]">
<option>
<option>
<option>
</select>
while validating the form in the end. How do i go about it? I dont use ids along with the name, because I think it might make it complex.
I would recommend you to stay with the 'dropdown[]' name, then you can use the getElementsByName function, which will return you an array that you can iterate, of elements with the given name in the document:
var dropdownArray = document.getElementsByName('dropdown[]'),
i, element, n = dropdownArray.length;
for (i = 0; i < n; i++) {
element = dropdownArray[i];
// you can check the value of each element here...
}
Edit: Modifying your code:
function addup(){
var tot = 0, i, // i declaration was missing
dropdowns = document.payment.elements['dropdown[]'];
for(i = 0;i<dropdowns.length;i++) {
//alert(i);
var find = dropdowns[i];
var check = find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay') {
// not using eval anymore
var tot1 = document.payment.elements[check.substring(4)+'_amount'].value;
//alert(tot1);
tot += +tot1; // unary plus operator to convert to number
}
document.payment.total_amount.value=tot;
calcTotal();
}
}
I think you're approaching this problem wrong. You should probably use "id" to uniquely identify elements. Then you can use one of the many libraries available for free (jQuery, dojo query, ....) to provide you a nicer way to select elements from the page. Either by giving your specific "<select>" elements class names, or just by finding all the "select" elements on the page.
I'm completely in the dark as to why "[]" at the end of the name would make a difference for you. But I'm not familiar with php.
Using this box because i could display the code.
If i named the element as "dropdown[]" I would be getting an error like in this case:-
function addup(){
var tot=0;
for(i=0;i<(document.payment.dropdown.length);i++)
{
//alert(i);
var find=document.payment.dropdown[][i];
var check=find.options[find.selectedIndex].value;
//alert(check);
if(check.substring(0,3)=='pay')
{
var other="document.payment."+check.substring(4)+"_amount.value";
var tot1=eval(other);
//alert(tot1);
tot+=parseInt(tot1);
}
document.payment.total_amount.value=tot;
calcTotal();
}
}
Pardon the shabby code, but this doesnt seem to work if i name it as "dropdown[]". So i need the name to be "dropdown" in the beginning and then it should change to "dropdown[]" onsubmit.
I've just found your question.
Why to just add a id (example 'itsID') tag to your select and then point it to change its name with:
var ref = document.getElementById('itsID');
ref.name = "dropdown[]";
It works for me with ref.

Categories

Resources