The scenario is: User choose a entry from dropDown list. Referring to the relevant entry i will create a new prefix for the webpath existing in . But the problem I have, the will not interpret as a link part, so the link won't be generated!
Use Case: If User choose link1 from dropDown-list, the result should be:https://link1//web/sso/bw/ostrfer.jsp (as link and as text display)
Could you help me how I can reach this?
Many thanks for your help! :)
JS:
function output (choice) {
var index = choice.selectedIndex;
var prefix = "";
if(index == 1)
prefix = "https://link1";
else if (index == 2)
prefix = "https://link2;
else if (index == 3)
prefix = "https://link3";
else if (index == 4)
prefix = "https://link4";
else if (index == 5)
prefix = ""https://link5";
document.getElementById("url").innerHTML = praefix;
}
HTML:
<body>
<form>
<p>
<select id = "list" name = "list" onchange ='output(this.form.liste);' >
<option></option>
<option>link1</option>
<option>link2</option>
<option>link3</option>
<option>link4</option>
<option>link5</option>
</select>
</p>
</form>
</span>/web/sso/bw/ostrfer.jsp> <span id = "url"></span> /web/sso/bw/ostrfer.jsp
</body>
See this demo:
http://jsfiddle.net/JFqrH/3/
HTML:
<form>
<p>
<select id = "list" name = "list" onchange ='output(this);' >
<option></option>
<option>link1</option>
<option>link2</option>
<option>link3</option>
<option>link4</option>
<option>link5</option>
</select>
</p>
<a id="url" href="/web/sso/bw/ostrfer.jsp">/web/sso/bw/ostrfer.jsp</a>
<a id="url1" href="/web/sso/bw/ostrfer.jsp">/web/sso/bw/ostrfer1.jsp</a>
<a id="url2" href="/web/sso/bw/ostrfer.jsp">/web/sso/bw/ostrfer2.jsp</a>
</form>
JS:
function output (choice) {
var index = choice.selectedIndex;
var prefix = "";
if(index == 1)
prefix = "https://link1";
else if (index == 2)
prefix = "https://link2";
else if (index == 3)
prefix = "https://link3";
else if (index == 4)
prefix = "https://link4";
else if (index == 5)
prefix = "https://link5";
updateLink(document.getElementById("url"), prefix);
updateLink(document.getElementById("url1"), prefix);
updateLink(document.getElementById("url2"), prefix);
}
function updateLink(url, prefix) {
if(!url.getAttribute("postfix")) {// need to save orignal href as it will be replaced later
url.setAttribute("postfix", url.getAttribute("href"));
}
var postfix = url.getAttribute("postfix");
url.innerHTML = prefix + postfix;
url.href = prefix + postfix;
}
You have multiple syntax errors in your code. Plus a href=<span id = "url"></span> is nonsence. It can't work. Instead of that you should use attributes (see getAttribute/setAttribute). Also, it is much simpler to use swithc statement instead of if/else. Another thing: onchange=output(this.form.liste); - instead of this you can use onchange=output(this); as this will already point to your dropdown element there.
The question is pretty unclear, does this work?
document.getElementById("url").innerHTML = prefix + document.getElementById("url").innerHTML;
You could store the this snippet:
/web/sso/bw/ostrfer.jsp
as a constant like so:
var uri = "/web/sso/bw/ostrfer.jsp";
Then when the user selects the link you could append it like so:
var elem = document.getElementById("url");
elem.setAttribute('href', prefix + uri);
This should update the "href" attribute of the anchor tag with the new url.
I setup a test example so you can see it in action in this Fiddle. If you inspect the link with the browsers developer tools you can see that the href (originally an empty string "") has now been updated after executing the code to be "https://link1/web/sso/bw/ostrfer.jsp".
Hope this helps.
You have multiple syntax errors that are causing the problem:
First
prefix = "https://link2;
^ missing close quote here
Second
prefix = ""https://link5";
^ remove the extra quote here
Third
document.getElementById("url").innerHTML = praefix;
^ should be prefix
Fourth
<select id = "list" name = "list" onchange ='output(this.form.liste);' >
^ should be list or just 'this'
Even with the syntax errors, your code is still not right - it's not good to have a <span> within the href of an <a>.
Try this jsFiddle Demo - I changed the way the code works, it doesn't use the span.
Full fixed code:
<script>
function output () {
var index = this.selectedIndex;
var prefix = "";
var suffix = "/web/sso/bw/ostrfer.jsp";
prefix = "https://" + this.value;
var link = document.getElementById("url");
link.href = prefix + suffix;
link.innerHTML = prefix + suffix;
}
window.onload = function()
{
document.getElementById("list").onchange = output;
}
</script>
<form>
<p>
<select id = "list" name = "list" >
<option></option>
<option>link1</option>
<option>link2</option>
<option>link3</option>
<option>link4</option>
<option>link5</option>
</select>
</p>
</form>
Related
In a formstack form, I need to be able to pass a list to the form as a parameter and, from that list, create checkboxes or dropdown menus that the user can select and that are saved in formstack's database and sent to integrations like all other fields. Here's an example of what I'd like to send in:
http://theformurl?list=option1,option2,option3,option4
From this, I'm trying to use code insertion in either (or a mixture of) the head, footer, or a code embed to create a new field on load that looks and acts like all the other fields.
I've been tinkering with Jenna Molby's approach to dynamically modifying html with url parameters found here:
https://jennamolby.com/tutorial-examples/dynamic-content-based-on-a-url-parameter-example/
But no luck so far. At present, I've not succeeded in getting dynamic text to populate in the form, let alone a form field that then talks to formstack's back end.
Is this doable, and if so, can anyone recommend an approach or a thread to pull on to figure it out?
--update
Thanks to Eric's suggestion, I was able to get halfway there. This code in the footer can commandeer a checkbox that you've already inserted in the form by id. It will replace that checkbox with the values you send in the url. But the selections don't get caught by Formstack when you submit.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put field number in var fieldNumber
var fieldNumber = "12345678";
//Put the parameter you're searching for in var param
var param = "parameter name";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "Prefix ";
//Put the question you want to ask here.
var theQuestion = "Which of the values that came through the url will you select?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "No variables were contained in the parameter.";
var theField = "field" + fieldNumber;
var theFieldID = "fsCell"+fieldNumber;
var values = url.searchParams.get(param).split(",");
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+ prefix + values[0] + "\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+fieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+(i+1)+"\" name=\""+theField+"[]\" value=\""+prefix+values[i]+"\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
}
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
</script>
Any thoughts on how to get it to talk to Formstack on submit?
Not familiar with formstack or what exactly you're getting from the URL and placing into forms or of what type, but I'll take a shot in the dark here.
Perhaps something like this:
var paramsToGet = ['param', 'param', 'param'];
document.addEventListener("DOMContentLoaded", function(event) {
let url = new URL(window.location.href);
paramsToGet.forEach((v)=>{
let thisParam = url.searchParams.get(param);
newFormElement(thisParam, x, x, "Default Value");
})
});
var newFormElement = (type, element_id, target_id, default_value) => {
default_value = default_value || null;
let el = document.createElement(type);
el.id = element_id;
if (default_value) {el.value = default_value;}
document.getElementById(target_id).appendChild(el);
}
So I've managed to find a solution that works for me. Thanks Eric for getting me started.
It requires adding two fields to the form you want to use this in: (1) a hidden text entry field where the selected values will be written, and (2) a placeholder checkbox field that this code will overwrite. You'll need to grab their id numbers, which I did by opening the live form and viewing source.
<script>
var selectedValues = [];
//This code goes in your Formstack theme footer. In the form that you want to add dynamic checkboxes to, create two fields using the WYSIWYG editor: a checkbox field and a text entry field. Make the text entry field hidden. You will need to know the id number of both the text entry and checkbox fields.
//Put the text entry field number in var textFieldNumber
var textFieldNumber = "field"+"12345678";
var index;
var checkboxFieldNumber = "12345679";
//Put the parameter you're searching for in var param
var param = "param";
//if you want a prefix before your values in the checkbox, use prefix
var prefix = "";
//Put the question you want to ask here.
var theQuestion = "Your question?";
//What should the single checkbox say if no parameters are passed?
var theDefaultBox = "Default message.";
document.addEventListener("DOMContentLoaded", function(event) {
var url = new URL(window.location.href);
//Put checkbox field number in var checkboxFieldNumber
//Build the replacement HTML for the placeholder checkbox field.
var theField = "field" + checkboxFieldNumber;
var theFieldID = "fsCell"+checkboxFieldNumber;
var values = url.searchParams.get(param).split(",") || null;
var theFieldHTMLfront = "";
if (values) {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>"+theQuestion+"</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+values[0]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[0] + "</label>";} else {theFieldHTMLfront = "<fieldset id=\"label"+checkboxFieldNumber+"\"><legend class=\"fsLabel fsLabelVertical\"><span>Which values may have observed or have knowledge about this event?</span></legend><div class=\"fieldset-content\"><label class=\"fsOptionLabel vertical\" for=\""+theField+"_1\"><input type=\"checkbox\" id=\""+theField+"_1\" name=\""+theField+"[]\" value=\""+theDefaultBox+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />test</label>";}
var theFieldHTMLback = "</div></fieldset>";
//iterate through the array found in the url parameters, adding a new checkbox option for each element in the array.
if (values) {for (var i = 1; i < values.length; i++) {
theFieldHTMLfront += "<label class=\"fsOptionLabel vertical\" for=\""+theField+(i+1)+"\"><input type=\"checkbox\" id=\""+theField+"_"+(i+1)+"\" name=\""+theField+"[]\" value=\""+values[i]+"\" onchange=\"checkBoxToggle(this)\" class=\"fsField vertical\" />"+ prefix + values[i] + "</label>";
};}
//finalize replacement HTML
var theFieldHTML = theFieldHTMLfront + theFieldHTMLback;
//write new HTML to DOM
document.getElementById(theFieldID).innerHTML = theFieldHTML;
});
function checkBoxToggle(thisBox) {
if(thisBox.checked) {
//When a new checkbox is selected, add its value to array selectedValues, sort it, and write it to the text entry field.
selectedValues.push(thisBox.value);
selectedValues.sort();
document.getElementById(textFieldNumber).value = selectedValues;
} else {
//When a checkbox is deselected, splice its value out of array selectedValues and write the array to the text entry field's value
index = selectedValues.indexOf(thisBox.value);
if (index > -1) {
selectedValues.splice(index, 1);
document.getElementById(textFieldNumber).value = selectedValues;
}
}
}
</script>
I have the following JavaScript which build url paramters based on users input:-
$(document).ready(function(){
$('#button').click(function(e) {
var count=1;
var s="";
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if(inputvalue!=null && inputvalue!="")
{
s = s+ "FilterField"+count+"=Journal&FilterValue"+count+"="+inputvalue+"&";
count++;
}
if(inputvalue2!=null && inputvalue2!="")
{
s = s+ "FilterField"+count+"=KeyWords&FilterValue"+count+"="+inputvalue2+"&";
count++;
}
if(inputvalue3!=null && inputvalue3!="")
{
s = s+ "FilterField"+count+"=datepub&FilterValue"+count+"="+inputvalue3+"&";
count++;
}
if(inputvalue4!=null && inputvalue4!="")
{
s = s+ "FilterField"+count+"=Title&FilterValue"+count+"="+inputvalue4+"&";
count++;
}
if(inputvalue5!=null && inputvalue5!="")
{
s = s+ "FilterField"+count+"=localcurrency&FilterValue"+count+"="+inputvalue5+"&";
count++;
}
if(inputvalue6!=null && inputvalue6!="")
{
s = s+ "FilterField"+count+"=locations&FilterValue"+count+"="+inputvalue6+"&";
count++;
}
if(inputvalue7!=null && inputvalue7!="")
{
s = s+ "FilterField"+count+"=dropdown1&FilterValue"+count+"="+inputvalue7+"&";
count++;
}
if(inputvalue8!=null && inputvalue8!="")
{
s = s+ "FilterField"+count+"=dropdown2&FilterValue"+count+"="+inputvalue8+"&";
count++;
}
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+s);
});
});
</script>
now the above script will generate URLs such as
http://***/teamsites/Bib%20Test/Forms/search.aspx?FilterField1=Journal&FilterValue1=123
http://***/teamsites/Bib%20Test/Forms/search.aspx?FilterField1=Journal&FilterValue1=123&FilterField2=localcurrency&FilterValue2=USD&
and thing were working well, till i tried passing a search parameter which contain &. for example i wanted to search for a record which have their journal = General&Procedure, so using my above code, the URL will be as follow:-
http://***/teamsites/Bib%20Test/Forms/search.aspx?FilterField1=Journal&FilterValue1=General&Procedure&
and i did not get any result,, as the application assume that the Procudure is a parameter and not part of the FilterValue1.. now to fix this specific problem, i define to build the URL parameters with encodeURIComponent() function as follow:-
var inputvalue = encodeURIComponent($("#journal").val());
var inputvalue2 = encodeURIComponent($("#keywords").val());
var inputvalue3 = encodeURIComponent($("#datepub").val());
var inputvalue4 = encodeURIComponent($("#title").val());
var inputvalue5 = encodeURIComponent($("#localcurrency").val());
var inputvalue6 = encodeURIComponent($("#locations").val());
var inputvalue7 = encodeURIComponent($("#dropdown1").val());
var inputvalue8 = encodeURIComponent($("#dropdown2").val());
now the generated URL will be as follow:-
http://***teamsites/Bib%20Test/Forms/search.aspx?FilterField1=Journal&FilterValue1=General%26Procedure
and i got the expected results..
but not sure if using encodeURIComponent() to only encode the parameter values is a valid fix,, as seems i will be encoding the & if it is part of the query string parameter,, but still the url contain non-encoded & which separate the url parameters .. now the result i got from the last url is correct.. but not sure if i am doing things correctly ? and is there a built-in function to do this work for me ??
Thanks
Here are sources for URL syntax:
Easily understandable and authoritative enough:
Components: https://en.wikipedia.org/wiki/Uniform_Resource_Identifier#Syntax
Query component: https://en.wikipedia.org/wiki/Query_string
Percent-encoding of non-allowed characters: https://en.wikipedia.org/wiki/Percent-encoding
Uniform Resource Identifier (URI): Generic Syntax (RFC 3986) https://www.rfc-editor.org/rfc/rfc3986
Components: https://www.rfc-editor.org/rfc/rfc3986#section-3
Query component: https://www.rfc-editor.org/rfc/rfc3986#section-3.4
Percent-encoding: https://www.rfc-editor.org/rfc/rfc3986#section-2.1
You will notice that the exact content of the query component is not standardized. Its simple definition is:
The query component is indicated by the first question
mark ("?") character and terminated by a number sign ("#") character
or by the end of the URI.
However, the de-facto standard is to use ampersand (&) character as delimiter. With this convention, anytime this character also appears in your data and is not meant to be a delimiter, you have to "percent-encode" it, as per the standard as well:
A percent-encoding mechanism is used to represent a data octet in a component when that octet's corresponding character is outside the allowed set or is being used as a delimiter of, or within, the
component.
You will easily understand that other special characters, like =, % and # must also be percent-encoded, should they appear in your data. There is no harm in encoding even more special characters as well.
Therefore if you follow this convention, your query component should be of the form:
?field1=value1&field2=value2
with each field and value being percent-encoded. In JavaScript, you can indeed conveniently use the encodeURIComponent function. Do not forget to encode the fields as well!
Furthermore, as your use case is very common, there are plenty libraries available that can handle such conversion for you, e.g. URI.js.
But since you mention using jQuery, you can conveniently use jQuery.param to do the conversion:
Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties.
$(document).ready(function() {
$('#button').click(retrieveInputsValues);
retrieveInputsValues();
});
function retrieveInputsValues() {
var inputIds = [
'Journal',
'KeyWords',
'datepub',
'Title',
'localcurrency',
'locations',
'dropdown1',
'dropdown2'
];
var obj = {};
var count = 1;
var value;
for (var i = 0; i < inputIds.length; i += 1) {
value = $('#' + inputIds[i].toLowerCase()).val();
if (value !== null && value !== '') {
obj['FilterField' + count] = inputIds[i];
obj['FilterValue' + count] = value;
count += 1;
}
}
console.log($.param(obj));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
Journal
<input type="text" id="journal" value="test & ampersand, comma, % percent, = equal and space" />
<br />keywords <input type="text" id="keywords" />
<br />datepub
<select id="datepub">
<option value=""></option>
<option value="1950">1950</option>
<option value="2010">2010</option>
<option value="2017" selected>2017</option>
<option value="audi">Audi</option>
</select>
<br />title
<select id="title">
<option value=""></option>
<option value="TestDoc">test doc</option>
<option value="t">t</option>
</select>
<br />localcurrency
<select id="localcurrency">
<option value=""></option>
<option value="USD">USD</option>
</select>
<br />locations
<select id="locations">
<option value=""></option>
<option value="US">US</option>
<option value="UK">UK</option>
</select>
<br />dropdown1
<select id="dropdown1">
<option value=""></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<br />dropdown2
<select id="dropdown2">
<option value=""></option>
<option value="aa">aa</option>
<option value="bb">bb</option>
<option value="cc">cc</option>
<option value="dd">dd</option>
</select>
<br />
<button type="button" id="button">search</button>
<!-- re-used from https://stackoverflow.com/a/47008115/5108796 -->
BTW, usually there is no need to pass the field names as values, just "field=value" is used.
But you may have specific use case for your back-end processing?
Extending my comment as an answer.
Using encodeURIComponent is not only valid and correct, it is actually the only fix for supporting special characters in values in URL which have special meaning for a URL.
Encoding the values in URL component is important for prevent XSS attacks as well. Have a look here
URL-escaping is susceptible to double-escaping, meaning you must
URL-escape its parts exactly once. It is best to perform the
URL-escaping at the time the URL is being assembled.
However, you can improve your code in the following manner
var inputs = [ "#journal", "#keywords", "#datepub", "#title", "#localcurrency", "#locations", "#dropdown1", "#dropdown2" ];
$(document).ready(function(){
$('#button').click(function(e) {
var count = 1;
var searchParams = inputs.filter( function( id ){
return $( "#" + id ).val().trim().length > 0;
}).map( function( id ){
var value = encodeURIComponent( $( "#" + id ).val().trim() );
return "FilterField" + (count) + "=" + id + "&FilterValue" + (count++) + "=" + value;
}).join( "&" );
window.location.replace("/teamsites/Bib%20Test/Forms/search.aspx?"+ searchParams );
});
});
Alternatively, you can also use URL (though not supported in IE)
var inputs = [ "#journal", "#keywords", "#datepub", "#title", "#localcurrency", "#locations", "#dropdown1", "#dropdown2" ];
$(document).ready(function(){
$('#button').click(function(e) {
var count = 1;
var url = new URL( "/teamsites/Bib%20Test/Forms/search.aspx?", window.location.origin );
inputs.forEach( function( id ){
var value = encodeURIComponent( $( "#" + id ).val().trim() );
if ( value.length > 0 )
{
url.searchParams.append( "FilterField" + count, id );
url.searchParams.append( "FilterValue" + (count++), value );
}
});
window.location.replace( url.href );
});
});
As you can see that in this approach as well, you will have to use encodeURIcomponent since as per spec
The append(name, value) method, when invoked, must run these steps:
Append a new name-value pair whose name is name and value is value, to
list.
Run the update steps.
there is no guarantee that encoding will be done. So, the explicit encoding necessary!!.
/!\ THIS IS NOT AN ANSWER
In relation with comments
const [
$("#journal").val(),
$("#keywords").val(),
$("#datepub").val(),
$("#title").val(),
// ...
].forEach((x) => {
if (x !== null && x !== '') {
s += ...;
count += 1;
}
});
I use encodeUriComponent for this.
url += "&filter=" + encodeURIComponent(filter);
You want '&' inside the parameter value to be encoded, so you use 'encodeURIComponent' on the value of the parameter, but you don't want to encode the stuff between parameters.
Use this if you are not concerned about Internet Explorer or Edge.
I would recommend to use browser's URL API instead. It is stable and is available in most of the modern browsers to deal with URL specific work natively.
Your code can be changed as follows to use this API. It automatically encodes all the required parameters as per the specs. You don't need to deal with the query parameters manually.
$(document).ready(function() {
$('#button').click(function(e) {
var count = 1;
var s = "";
var url = new URL("http://yourhost.com/teamsites/Bib%20Test/Forms/search.aspx");
var inputvalue = $("#journal").val();
var inputvalue2 = $("#keywords").val();
var inputvalue3 = $("#datepub").val();
var inputvalue4 = $("#title").val();
var inputvalue5 = $("#localcurrency").val();
var inputvalue6 = $("#locations").val();
var inputvalue7 = $("#dropdown1").val();
var inputvalue8 = $("#dropdown2").val();
if (inputvalue != null && inputvalue != "") {
url.searchParams.set("FilterField" + count, "Journal");
url.searchParams.set("FilterValue" + count, inputvalue);
count++;
}
if (inputvalue2 != null && inputvalue2 != "") {
url.searchParams.set("FilterField" + count, "KeyWords");
url.searchParams.set("FilterValue" + count, inputvalue2);
count++;
}
if (inputvalue3 != null && inputvalue3 != "") {
url.searchParams.set("FilterField" + count, "datepub");
url.searchParams.set("FilterValue" + count, inputvalue3);
count++;
}
if (inputvalue4 != null && inputvalue4 != "") {
url.searchParams.set("FilterField" + count, "Title");
url.searchParams.set("FilterValue" + count, inputvalue4);
count++;
}
if (inputvalue5 != null && inputvalue5 != "") {
url.searchParams.set("FilterField" + count, "localcurrency");
url.searchParams.set("FilterValue" + count, inputvalue5);
count++;
}
if (inputvalue6 != null && inputvalue6 != "") {
url.searchParams.set("FilterField" + count, "locations");
url.searchParams.set("FilterValue" + count, inputvalue6);
count++;
}
if (inputvalue7 != null && inputvalue7 != "") {
url.searchParams.set("FilterField" + count, "dropdown1");
url.searchParams.set("FilterValue" + count, inputvalue7);
count++;
}
if (inputvalue8 != null && inputvalue8 != "") {
url.searchParams.set("FilterField" + count, "dropdown2");
url.searchParams.set("FilterValue" + count, inputvalue8);
count++;
}
window.location.replace(url.href);
});
});
In addition to it, I recommend to incorporate the suggestions from #GrégoryNEUT, as it makes the code concise and easy to read.
I'm trying to make an input that filters a <ul> based on the value in pure JavaScript. It should filter dynamically with the onkeyup by getting the li's and comparing their inner element name with the filter text.
Here is my function:
var searchFunction = function searchFeature (searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
stringValue.onkeyup = function () {
//toUpperCase to make it case insensitive
var filter = stringValue.toUpperCase();
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = eachStudent[i].getElementsByClassName('student-details')[1].innerHTML;
//display all the results where indexOf() returns 0
if (name.toUpperCase().indexOf(filter) == 0)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}}
My HTML for the search bar:
<div class="student-search">
<input id="inputSearch" placeholder="Type name here.." type="text"> <button>Search</button></div>
My HTML for one of the li's:
<ul class="student-list">
<li class="student-item cf">
<div class="student-details">
<img class="avatar" src="#">
<h3>John Doe</h3>
<span class="email">John.Doe#example.com</span>
</div>
<div class="joined-details">
<span class="date">Joined 01/01/14</span>
</div>
</li>
I would like to filter all the elements (name, email, joined date) based on the value of the input.
Unfortunately, I don't get any errors and it's simply not working.
The function is correctly invoked because the console.log prints...
Here goes the codepen: http://codepen.io/Delano83/pen/qaxxjA?editors=1010
Any help or comments on my code is very appreciated.
There were several issues:
stringValue.onkeyup - stringValue is the value. You can't onkeyup it.
var eachStudent = document.querySelector(".student-item"); will fetch the first thing with student-item class. You need to use querySelectorAll or just use jquery's $('.find-item').
if (name.toUpperCase().indexOf(filter) == 0) indexOf returns 0 if the filter is found at the beginning of the name. 0 as match if found at index 0. You need to check against -1, which means it was not found at all.
Otherwise it more or less worked, good job.
I also added Jquery for me to fix it faster. If you insist on using pure javascript I am sure you will be able to edit it.
Check it out here: http://codepen.io/anon/pen/WGrrXW?editors=1010. Here is the resulting code:
var page = document.querySelector(".page");
var pageHeader = document.querySelector(".page-header");
var studentList = document.querySelector(".student-list");
var eachStudent = document.querySelectorAll(".student-item");
var studentDetails = document.querySelector(".student-details");
//Recreate Search Element in Js
var searchBar = function createBar(searchString) {
var studentSearch = document.createElement("div");
var input = document.createElement("input");
var searchButton = document.createElement("button");
input.type = "text";
var txtNode = document.createTextNode("Search");
if (typeof txtNode == "object") {
searchButton.appendChild(txtNode);
}
studentSearch.setAttribute("class", "student-search");
input.setAttribute("id", "inputSearch");
//append these elements to the page
studentSearch.appendChild(input);
studentSearch.appendChild(searchButton);
input.placeholder = "Type name here..";
return studentSearch;
}
var searchFunction = function searchFeature(searchString) {
console.log("Is my search feature working?");
//Get the value entered in the search box
var inputString = document.getElementById('inputSearch');
var stringValue = inputString.value;
//Onkeyup we want to filter the content by the string entered in the search box
inputString.onkeyup = function() {
//toUpperCase to make it case insensitive
var filter = $(this).val().toUpperCase()
//loop through all the lis
for (var i = 0; i < eachStudent.length; i++) {
//Do this for all the elements (h3, email, joined-details, date)
var name = $(eachStudent[i]).find('h3').text()
console.log(name, filter, name.toUpperCase().indexOf(filter))
//display all the results where indexOf() does not return -1
if (name.toUpperCase().indexOf(filter) != -1)
eachStudent[i].style.display = 'list-item';
else
eachStudent[i].style.display = 'none';
}
}
}
function addElements() {
console.log('Add search bar, trying to anyway...')
pageHeader.appendChild(searchBar());
// page.appendChild(paginationFilter());
onLoad();
}
window.onload = addElements;
window.onLoad = searchFunction;
Should be straightforward, but I just can't work out why this will not work! I'm a n00b, first off.
I have two input boxes that users need to fill in, a name and an amount. If these have been filled in, I change the query string on the URL, if not, then I give them a pre-defined query string for the URL.
I can't get a working jsfiddle, as something weird is going on with the & signs for my query string, sigh.
Basically, I cannot get the URL to change on click.
So here's my code, and the non-working jsfiddle for those interested: http://jsfiddle.net/9uk68m6x/
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(){
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if (nameVal != ''){
//if name value isn't blank, then
$("a.makeUrl").prop("href", url+'&name='+nameVal+'&free_amount=1&amount='+amountVal+'00');
}
else (nameVal == ''){
$("a.makeUrl").prop("href", "http://www.website.com&free_amount=1&amount=200");
}
});
});
</script>
Donate
</form>
There is a syntax error in your script: else do not accept any kind of arguments. Use else if instead. However, since your condition is binary (nameVal is either empty or not), then you can actually make do without the second if statement.
Therefore, some changes I have made:
Revise the conditional statement. You simply have to check if nameVal is empty or not using the expresison !nameVal.
Change the href attribute using .attr() instead of .prop().
Use $(this) in the click function since it is cached
Here is the fiddle: http://jsfiddle.net/teddyrised/9uk68m6x/4/
$(function () {
$('.makeUrl').click(function (e) {
// Declare variables
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
// Conditional statement
if (nameVal) {
//if name value isn't blank, then
$(this).attr("href", url + '&name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$(this).attr("href", "http://www.website.com&free_amount=1&amount=200");
}
// Check updated href
console.log($(this).attr("href"));
});
});
You need to have a ? in there somewhere. A valid parameterized URL would be:
"http://www.website.com/?free_amount=1&amount=200"
Yeah, that is kinda hard to fiddle when they encode those characters for you before it runs.
After a couple changes to your JS, it seems to be working, at least in JSFiddle.
$(function () {
$('.makeUrl').click(function () {
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
if( nameVal !== "" ) {
//if name value isn't blank, then
$("a.makeUrl").prop("href", url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00');
} else {
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
});
});
You had a syntax error at the else. Remove the (newVal == '') or use else if
Anyway, here is a working jsfiddle what is show you the URL. (Prevent to activate the link, because of e.preventDefault();
And it's checkin the amountVal also.
<form>
<input type="text" class="name">
<input type="text" class="amount">
<script type="text/javascript">
$(function() {
$('.makeUrl').click(function(e) {
e.preventDefault();
var url = 'http://www.website.com',
nameVal = $("input.name").val(),
amountVal = $("input.amount").val();
var newUrl;
if (nameVal !== '' && amountVal != '') {
//if name value isn't blank, then
newUrl = url + '?name=' + nameVal + '&free_amount=1&amount=' + amountVal + '00';
$("a.makeUrl").prop("href", newUrl);
} else {
newUrl = 'http://www.website.com&free_amount=1&amount=200';
$("a.makeUrl").prop("href", "http://www.website.com?free_amount=1&amount=200");
}
$('#url').html(newUrl);
});
});
</script>
Donate
</form>
<div>URL is: <span id="url"></span></div>
I'm making a quiz with a text input. This is what I have so far:
<html>
<head>
<script type="text/javascript">
function check() {
var s1 = document.getElementsByName('s1');
if(s1 == 'ō') {
document.getElementById("as1").innerHTML = 'Correct';
} else {
document.getElementById("as1").innerHTML = 'Incorrect';
}
var s2 = document.getElementsByName('s2');
if(s2 == 's') {
document.getElementById("as2").innerHTML = 'Correct';
} else {
document.getElementById("as2").innerHTML = 'Incorrect';
}
//(...etc...)
var p3 = document.getElementsByName('p3');
if(p3 == 'nt') {
document.getElementById("ap3").innerHTML = 'Correct';
} else {
document.getElementById("ap3").innerHTML = 'Incorrect';
}
}
</script>
</head>
<body>
1st sing<input type="text" name="s1"> <div id="as1"><br>
2nd sing<input type="text" name="s2"> <div id="as2"><br>
<!-- ...etc... -->
3rd pl<input type="text" name="p3"> <div id="ap3"><br>
<button onclick='check()'>Check Answers</button>
</body>
</html>
Every time I check answers it always says Incorrect and only shows the first question. I also need a way to clear the text fields after I check the answers. One of the answers has a macro. Thanks in advance.
The method getElementsByName returns a NodeList, you can't really compare that against a string. If you have only one element with such name, you need to grab the first element from that list using such code instead:
var s1 = document.getElementsByName('s1')[0].value;
To make it more flexible and elegant plus avoid error when you have typo in a name, first add such function:
function SetStatus(sName, sCorrect, sPlaceholder) {
var elements = document.getElementsByName(sName);
if (elements.length == 1) {
var placeholder = document.getElementById(sPlaceholder);
if (placeholder) {
var value = elements[0].value;
placeholder.innerHTML = (value === sCorrect) ? "Correct" : "Incorrect";
} else {
//uncomment below line to show debug info
//alert("placeholder " + sPlaceholder+ " does not exist");
}
} else {
//uncomment below line to show debug info
//alert("element named " + sName + " does not exist or exists more than once");
}
}
Then your code will become:
SetStatus('s1', 'ō', 'as1');
SetStatus('s2', 's', 'as2');
//...
document.getElementsByName('s1') is an array you should use document.getElementsByName('s1')[0] to get certain element(first in this case)