Pass searchbox text as query param - javascript

I'm new to javascript.
When user enters any text or if he clicks on the search icon, i need to get the search text value and pass on that value as query param and redirect it to search results page.
Issue here is , when the page got loaded it directly redirects to the search results page without entering any text. Could you please let me know what i'm doing wrong ?
http://localhost:3000/search/searchresults.html?query=&filter=newsroom&site=allsite_all&ei=r1_search
// Only run function if the newssearch search field exists
if ($('#search_banner-q_newsroom').length >= 1) {
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch());
}
function setupNewsroomSearch() {
var tracking;
if ($(".self-service-search").length > 0) {
tracking = "&ei=r2_pt_search";
} else {
tracking = "&ei=r1_search";
}
redirectToSearchPage($("#search_banner-q_newsroom").val(), "newsroom", "site_all", tracking);
}
<form class="search_box_wrapper">
<div class="search-box">
<input type="text" id="search_banner-q_newsroom" aria-label="Search" name="query" placeholder="Search" />
<i class="icon-magnifying-glass search_desktop-newsroom-submit"></i>
</div>
</form>

The issue is because you're calling the setupNewsroomSearch() function immediately on load and providing it's return value to the keypress handler. Instead you need to give the event handler the reference of the function, like this:
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch); // Note: () removed
Also note that the if statement is redundant. jQuery is tolerant of calling functions on jQuery objects which matched no elements. Here's a tidied version of your JS logic:
$("#search_banner-q_newsroom").on('keypress', setupNewsroomSearch);
function setupNewsroomSearch() {
var tracking = $(".self-service-search").length > 0 ? '&ei=r2_pt_search' : '&ei=r1_search';
redirectToSearchPage($(this).val(), 'newsroom', 'site_all', tracking);
}

Related

Use changed values in other page

I have a textfield:
Voornaam: <h3 class="title1">Kevin</h3>
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/><br/>
I can set a value of this using this function:
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
Now in my other page, I want to use the value. I know I can for example pass a value from one page to another like this:
<a href='convert.php?var=data'>converteren.</a>
And then for example show it by doing this in the other page:
echo $_GET['var'];
But I cant really seem to figure out how to use the value which I've set using my textfield.
So my goal for now is to display the value I've set using my textfield in the other page using the method I just described.
Basically all I want to happen is for my textfield to change the value inside here aswell:
<a href='convert.php?var=data'>converteren.</a>
So where data is the value, I want it to become what I've put in the textfield.
Could anybody provide me with an example?
I've altered a bit your javascript code to make the link as you want.
To explain the answer, i've added document.getElementById("myLink").href="convert.php?var=" + myNewTitle ; which updates your a href while your function runs and is not empty.
function change1(){
var myNewTitle = document.getElementById('myTextField1').value;
if( myNewTitle.length==0 ){
alert('Write Some real Text please.');
return;
}
document.getElementById("myLink").href="convert.php?var=" + myNewTitle ;
var titles = document.getElementsByClassName('title1');
Array.prototype.forEach.call(titles,title => {
title.innerHTML = myNewTitle;
});
}
<a id="myLink" href='#'>converteren.</a>
Wrap your inputs inside a form element.
In the action attribute, specify the destination url.
In the method attribute, choose between GET and POST.
For example:
<form method="GET" action="convert.php">
<input type="text" id="myTextField1" />
<input type="submit" id="byBtn" value="Change" onclick="change1()"/>
</form>
Clicking the submit button will call "convert.php?myTextField1={value}".

ng-repeat not updating information after $scope was updated

I have an ng-repeat which creates a form with some starting data. Then the user is free to modify said data and the changes should appear in the form. Before that, the user submitted data are sanitized by another function, which is called by an ng-click on a button.
Everything works well under the hood (I checked my $scope.some_array, from which ng-repeat takes the data and the new data is in the right place) but nothing happens on the page.
The element:
<li ng-repeat="field in some_array" id="field-{{$index}}">
<div class="{{field.field_color}}">
<button type="button" ng-click="save_field($index)">done</button>
{{field.nice_name}}
</div>
<div id="field-input-{{$index}}">
<input type="text" id="{{field.tag}}" value="{{field.content}}">
<label for="{{field.tag}}">{{field.nice_name}}</label>
</div>
</li>
save_field code:
$scope.save_field = function (index) {
console.log($scope.some_array[index]["content"])
var value = $("#field-" + index).children("div").children("input").val()
var name = $scope.some_array[index]["name"]
var clean_value = my_clean(value)
if (norm_value === "") {
return
}
$scope.some_array[index]["content"] = clean_value
console.log($scope.some_array[index]["content"])
}
On the console I see:
10.03.16
10/03/16
Which is right, but in the form I only see 10.03.16. I already tried putting $timeout(function(){$scope.$apply()}) as the last line of my function, but the output is still the same.
You shouldn't use input like this if you want to bind a variable to it. Digest loop will refresh the value but it will not be updated visibly because this is not html native behavior.
Use ng-model instead, it will update view value of the input as expected:
<input type="text" id="{{field.tag}}" ng-model="field.content">
Also using ng-model your variable will be updated when user modify the input, so you can retrieve it to do some treatments much more easily in save_field function, without jQuery:
$scope.save_field = function (index) {
if (norm_value === "") {
return;
}
$scope.some_array[index]["content"] = my_clean($scope.some_array[index]["content"]);
};
More infos: https://docs.angularjs.org/api/ng/directive/ngModel

Create button which takes to a particular URL according to data in Form Field

I've two input form fields and i want when the user clicks a submit button he should be taken to a URL based on the input in these two fields. For example if the input in the two input fields is A and B respectively the condition should be set such that the User is taken to www.mydomain.com/C in Javascript. I DON'T want the values to be appended to the URL like www.mydomain.com/a/b which I already know how to.
I have seen lot of questions on SO and Google on URL Generation but none was the case as mine. I would really appreciate help from fellow SO users. Thanks in advance.
Do you mean something like this? This would take you to the address when both inputs have the value 'something' and the button is clicked.
<input type="text" id="a">
<input type="text" id="b">
<button onclick="go()">Go</button>
<script>
function go() {
if (document.getElementById('a').value == 'something' && document.getElementById('b').value == 'something') {
window.location = 'http://www.example.com/C';
}
}
</script>
If you are using jquery:
$( "form" ).submit(function() {
// TODO read your variables
// TODO apply conditions and redirect accordingly
if ( ... ) {
window.location = 'http://www.example.com/C'
} else {
window.location = 'http://www.example.com/D'
}
return false; // prevent default submit
});

How to check if a field has been populated with data using a javascript function?

Please note that i am a beginner in javascript. I've googled all the possible terms for my question but no luck. I wanted to know if there exists a javascript function that can be used to check if a field has been populated with data using another javascript function. No libraries please since i want to know the basics of javascript programming.
Edit:
I just wanted to clarify that scenario that i am into.
I have 3 input fields. These fields have their value assigned automatically by another javascript function. What i wanted to do is when this fields have their respected values i wanted to create a new input field that will calculate the sum of the value of the 3 fields.
As You are new Please try this whole code of HTML with Javascript code too.
<!DOCTYPE html>
<html>
<head>
<script>
function copyText()
{
var TextValue = document.getElementById("field1").value
if(TextValue !=''){
alert(TextValue);
}
alert();
}
</script>
</head>
<body>
<input type="text" id="field1" value="Hello World!"><br>
<button onclick="copyText()">Copy Text</button>
</body>
</html>
Hope this works.
Hope this helps you
//Html Code
<input type="text" value="sdsd" onChange="checkValue(this.value)">
//Java Script Code
function checkValue(value){
if((value).trim()!==""){
alert('return true');
}
else{
alert('return false');
}
}
//HTML line:
<input type="text" id="txtAddress" />
//JS code:
function setValue() {
//first we set value in text field:
document.getElementById('txtAddress').value = 'new value';
TestFunction();
}
function TestFunction() {
//second we will get value from this filed and check wether it contains data or not:
var address = document.getElementById('txtAddress').value;
if (address != "") {
alert("Yes, field contains address");
}
else {
alert("Empty field, there is no address");
}
}
I'm not sure what are you trying to achieve.
If you want to check if the input to the field was made with Javascript : there's no way to make that UNLESS your Javascript input function stores such information in some place (for example, add specific class to the modified object). Then you can proceed with following:
If you want to check if there's any value in the field then you can use onchange (triggers on change, you can pass the object to the function and get every property attached to it - value, class etc.).
example:
function changeValue( object )
{
object.value = "new value";
object.classList.add("modified");
}
function isChanged( object )
{
if( object.classList.contains("modified") )
alert("I'm modified by JS!");
}
<input type="text" id="first" onchange="isChanged(this)">
It has been some time since I was writing JS, but this should work.
Edit: now I remember onchange triggers only, if element is edited by user, thus rendering onchange detection worthless. Well, you could use set interval with the following function:
function getModified() {
// somehow process with
// document.getElementsByClassName("modified");
}
setInterval( getModified(), 3000 ); // get JS modified elements every 3s
lets say this is your html field (text input for instance):
<input type="text" id="txtName" />
in order to get it's value with javascript, use document.getElementById('txtName').value - for example:
function alert_value() {
var value = document.getElementById('txtName').value;
alert(value);
}
hope that helps.
EDIT:
if this text field is added dynamically, i'd suggest including jQuery and set the following script:
$(function(){
$(document).on('keyup', '#txtName', function(){ alert($(this).val()) });
});

how to validate the below criteria on the text fields and display the pop up page on satisfying all the condition using javascript validation

**Below is the input text fileds**
<form:form commandName="DRCNdetails" id="frm1" method="POST" action="addNewDelayReason.do" >
<form:input id="text1" path="delayCategory" cssClass="padR10 boxSizing" maxlength="75"></form:input>
<form:input path="preFix" id="text2" cssClass="padR10 boxSizing" maxlength="6"> </form:input>
<form:input path="reasonValue" maxlength="150" id="reasonValue" cssClass="textbox width100" cssStyle="visibility:hidden"></form:input>
</form:form> <button class="btnStyle blueBtn" onclick="formvalidation(),validateSpecialCharacters()"> <span class="left">
Submit
on submit need to vaidate the id's "text1","text2" fileds , on successful validation should display the below pop up screen that is showLtBox('mask', 'addMisdReasonCode1'), the conditions are below:
should not allow the null values for both the fileds, and special characters,and integers and alert me accordingly , on satisying this criteria only it should display the pop up screen showLtBox('mask', 'addMisdReasonCode1')
As far as I understand the question, you need to create a validation function that would be triggered upon pressing the submit button.
I already see that you have created to function that would be triggered on "OnClick" operation, However the syntax is incorrect.
You need to separate between the two function using ";" and not ","
You need to use only one function for validation - this would be more readable than the code you have written.
The result should be returned to the onclick command.
Example:
change the attribute onclick as follows:
onclick="return FullValidation();"
Create new JavaScript function that includes the two validations and return validation result;
function FullValidation() {
var validationResultOK = formvalidation();
if (validationResultOK) {
validationResultOK = validateSpecialCharacters();
}
if (validationResultOK) {
// Popup alert should be here, I put alert as example.
alert("Out your message here");
}
return validationResultOK;
}
Use Javascript Regular expression..
var pattern = new RegExp(/^[a-zA-Z]{n}$/);
where n is number of charecters you want to accept.
the above regular expression matches only charecters(both cases).
Now retrieve the value from your text fields
var text1 = document.getElementById("#your_id").value;
var text2 = document.getElementById("#your_id").value;
if(pattern.test(text1) && pattern.test(text2))
{
// your popup code
}

Categories

Resources