Generating search links using text input in javascript - javascript

Im trying to make a website which makes searches easy for me.
I want to be able to write any text in a text box, and make a java script generate the appropriate links.
Ive been trying this:
function prepare_link() {
var url_param = document.getElementById('url_param');
var target_link = document.getElementById('target_link');
if ( ! url_param.value ) {
return false;
}
target_link.href = target_link.href + escape(url_param.value);
}
<input type="text" name="url_param" id="url_param" onkeypress='prepare_link()' onKeyUp='prepare_link()' />
<input type="button" onclick="prepare_link();" value="Generate" /><br>
Google<br>
Bing
For some reason the search string is repeated, but i would like it to update links for each keypress and not just when i hit the generate button.
Moreover the second links isn't being updated :(
Any ideas? :)

Please have a look of the following code snippet, hope this will help to resolve your Issue.
In the following snippet you will not get the repeated values. Also, it will work with 'keyup' and 'click' event :
var google = "https://www.google.dk/search?q=";
function prepare_link() {
var target_link = document.getElementById('target_link');
target_link.href = google + escape(url_param.value);
alert(target_link.href);
}
void function () {
document.addEventListener("keyup", function(e) {
prepare_link();
e.preventDefault();
});
var click = document.getElementById("target_link");
click.addEventListener("click", function() {
document.dispatchEvent(keyEvent);
});
}();
<input type="text" name="url_param" id="url_param" value=""/>
<input type="button" value="Generate" onclick="prepare_link();" /><br>
Google<br>
Thanks :)

Related

Unable to change a value inside a variable?

I am currently working on a project that I took over with the input reads from a barcode, currently iam having trouble with my output giving me a fix value which the code reads from and does not read from the actual input.
below is the html code for the scanner. it reads fine
<div class="section" id="instruction-3">
<p>Otherwise, scan your code at the bottom, or manually type it in here:</p>
<span>
<input type="text" id="IC-input" name="IC" onclick="openKeyboard()" onkeyup="autofill(this.value)" placeholder="Enter your IC Number" required maxlength="9">
<label><button type="button" id="theButton" onclick="theButtonIsPressed()">Submit</button></label>
</span>
</div>
follow by the javascript (which i suspect is where the problem lies but am not sure)
<script>
var NRIC = '{"NRIC":"0"}';
function theButtonIsPressed(){
closeKeyboard();
console.log('button clicked');
NRIC = '{"NRIC":"123456789"}';
//var IcNum = document.getElementById("IC-input").value;
//NRIC = NRIC.replace("0", IcNum);
document.getElementById("IC-input").value = "";
doWork(NRIC)
}
</script>
function doWork(NRIC) {
// ajax the JSON to the server
$.post("receiver", NRIC, function(){
});
// stop link reloading the page
function update() {
setInterval(function(){$.post("receiver", '{"NRIC":NRIC}', function(){});}, 900);
It keeps giving me the value inside NRIC = '{"NRIC":"123456789"}'; which is 123456789, i realize this might be a simple fix but i am still learning and am unsure.
thank you in advance.
If I correctly understanded you want to have in the obj the input value, so try this:
function theButtonIsPressed(){
closeKeyboard();
console.log('button clicked');
var IcNum = document.getElementById("IC-input").value;
NRIC.NRIC = IcNum;
doWork(NRIC)
}
Why quotes around an object?
var NRIC = {"NRIC": 0};
function theButtonIsPressed() {
NRIC = {"NRIC": 123456789};
doWork(NRIC)
}
all but I have solved the problem, it was my fault that I did not mention I wanted to transfer the data to another webpage, and the problem with that was that the data was not transferred over to the other html.
function autofill(value){
console.log("Autofill:"+value)
//console.log(9 digits);
button = document.getElementById("theButton");
if(value.length == 9){
console.log('form is ready to submit');
theButtonIsPressed(value);
}
}
function theButtonIsPressed(value){
closeKeyboard();
console.log('button clicked');
//NRIC = '{"NRIC":"123456789"}';
console.log(value)
doWork(value)
}
by doing this it read the value as accordingly from the input and worked after, sorry again for my confusing question and thanks to everyone who tried to help.

Submit button and input validation?

I would like to change this code to work also when Enter is pressed to be more clear i got an submit form and an text field following with the submit button that has to be clicked to submit but that doesn't help me out as i need the form to recognize when enter is pressed, what would be the change to sort it out?
submitButton.onclick = function() {
index = 0;
results = [];
username = usernameInput.value;
if ( username.length > 0 ) {
window.location.href = '//' + window.location.host + window.location.pathname + '#' + username;
usernameInput.disabled = true;
submitButton.disabled = true;
getExistence();
}
Also i got an issue with input validation, what change should i made to allow the form recognize and accept special characters?
usernameInput.onchange = function() {
this.value = this.value.replace(/[^a-z0-9]+/ig, '').slice(0, 40);
var urlUsername = window.location.href.match(/\#([0-9a-z]{1,40})$/i)
I would ask from you to be more specific as i am new to javascript coding, and my knowledge it's not enough to sort it easily.
First solution is to read this.
https://www.tjvantoll.com/2013/01/01/enter-should-submit-forms-stop-messing-with-that/
You get info why "button type="submit" is better way than adding that into JS.
I think, solution for your problem can be something like that:
<form>
<label for="age">Age:</label>
<input type="number" min="0" max="120" name="age" id="age">
<button id="child">Child</button>
<button id="adult">Adult</button>
</form>
<script>
(function() {
var age = document.getElementById('age');
age.addEventListener('keypress', function(event) {
if (event.keyCode == 13) {
event.preventDefault();
if (age.value > 20) {
document.getElementById('adult').click();
} else {
document.getElementById('child').click();
}
}
});
}());
</script>
In short, commenting your code:
submitButton.onclick = function() { ... your code
This work as you describe, onclick. You can have similar function with :
submitButton.onkeypress = function() { ... same code with checking keyCode as example above
Validation: the simplest way to create any Regex is by doing some real test. I'am personally prefer this site: https://regex101.com/
What "special" character you mean? Because nobody can help right now. More info in this particular example. You just don't need any RegEx for JS. Accept any char and do everything on backend.

I want to join two inputs in one var at html on Wordpress

I'm using wordpress but making my own form for payments, i have two inputs of type select, like this:
<div id="S03" class="Selectos"><select tabindex="4" name="Mes" required="">
<option...[Code goes on]
And this:
<div id="S04" class="Selectos"><select tabindex="5" name="Ano" required="">
<option...[Code goes on]
Those works fine, but i want to join them in one input, i have research all day long, i found some clues about what i have to do, but in especifics no one does help me.
This is the input for the joining:
<input id="Expires" name="Expires" type="hidden" />
And the way i call the form:
<div class="container"><form id="contact" class="RV_donateForm" action="https://eps.banorte.com/secure3d/Solucion3DSecure.htm" method="post">
And how it close:
<fieldset><button id="contact-submit" name="submit" type="submit" data-submit=" ">Donar</button></fieldset>
</form></div>
Then i look for some way to joining and this one looks the better way to do it at the submit event:
<script type="text/javascript">
button.onclick = function (){
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value; cn = document.getElementById('Expires').value ;
alert(cn);
};
</script>
Well, at the bank 'post' they throw me all the vars ok, except for Expires that never joins and shows null, and i notice also because it never show me the alert. I'm new at html and JavaScript, and i'm not sure what could be wrong. All the code on the file are on this order for exception that the call of the form is at the beginning of everything, ¿maybe is the position on line that i have to put the javascript?
I appreciate any help. Thanks a lot stackfellas!
You may want to check this https://developer.mozilla.org/es/docs/Web/API/EventTarget/addEventListener
I guess you first need to get the button, then add the listener
<script type="text/javascript">
var button = document.getElementById('contact-submit')
button.addEventListener('click', function () {
document.getElementById('Expires').value = document.getElementById('S03').value + '/' + document.getElementById('S04').value;
cn = document.getElementById('Expires').value ;
alert(cn);
});
</script>
Finally! It does work like Omar says, but loading the addEventListener at onload body function, it will run the function that the event refers when you click on submit button.
<script type="text/javascript">
function putExpires(){
var cm = document.getElementById('S03').value;
var ca = document.getElementById('S04').value;
document.getElementById("Expires").value = cm + '/' + ca;
var cn = document.getElementById("Expires").value;
}
function load() {
var button = document.getElementById("contact-submit");
button.addEventListener("click", function(){putExpires()}, false);
}
</script>
<body onload="load();">
Thanks Omar!

Adding Tags to Highlighted Text in JS Not Working

I know many people have posted this exact question, but none of them are seeming to help me out. I am very new to Javascript, and I am trying to write a function that adds tags to the highlighted text in a Textarea.
Now my problem is it will not actually put the tags around the text. Here is my code:
HTML:
<textarea id="my_textarea" name="my_textarea"></textarea>
<br />
<input type="button" value="bold" onclick="formatText ('b');" />
<input type="button" value="italic" onclick="formatText ('i');" />
<input type="button" value="underline" onclick="formatText ('u');" />
JS:
function formatText(tag) {
var myTextArea = window.getSelection();
var myTextAreaValue = myTextArea.toString();
var updatedText = '<'+tag+'>' + myTextAreaValue + '</'+tag+'>';
myTextArea.value = updatedText;
}
Or simply the Fiddle. Now why it will not put the tags around the text I do not know. Please help me out! :) A new Javascript(er) here, it is not very similar to PHP...
You can use the following function (https://stackoverflow.com/a/14056768/1845408) to get the selected text:
$('input:button').click(function () {
var myTextAreaValue = $('#my_textarea').val();
var selectedText = getInputSelection($('#my_textarea'));
var updatedText = '<' + $(this).val() + '>' + selectedText + '</' + $(this).val() + '>';
myTextAreaValue = myTextAreaValue.replace(selectedText, updatedText);
$('#my_textarea').val(myTextAreaValue)
});
function getInputSelection(elem) {
if (typeof elem != "undefined") {
s = elem[0].selectionStart;
e = elem[0].selectionEnd;
return elem.val().substring(s, e);
} else {
return '';
}
}
<textarea id="my_textarea" name="my_textarea"></textarea>
<br />
<input type="button" value="b" />
<input type="button" value="i" />
<input type="button" value="u" />
Demo: https://jsfiddle.net/erkaner/0uoshu0s/3/
BTW for anyone who reads this. .click is really old and the newer .on is the best way to go because it covers any possible event that could happen!
I'm not sure what it is this is supposed to accomplish, but I can tell you right off the bat that it's not setting anything to myTextArea and another thing is that once it does update that variable is it supposed to do something with that variable or just leave a variable with the data saved to it. Also for fun don't forget to hit run on everytime you want to change the code.
The first thing I notice here is that you are trying to reinvent the wheel:
If you want to do something like this simply then you should be using libraries. They will take the work load off of you and let you worry about the logic of getting the job done.
JQuery: is where you should be looking first as it is one of many and of the most powerful web libraries at your disposal.
Debugging:
console.log(all the things!!!);
You should be using the console in the developer tools that come with your browser. press f12 on either ie or chrome and click on console to see the logs that you output. I know that Mozilla has one also but unsure on the button to open it. I have mine setup to open automatically if I need to debug.
Here is a pattern that you can use. I included the jquery library in the external dependencies tab already. The bold never would have worked. The html tag is .
Here is our HTML.
<textarea id="my_textarea" name="my_textarea"></textarea>
<br />
<input type="button" value="b" id="boldButton"/>
<input type="button" value="italic" id="italicButton" />
<input type="button" value="underline" id="underlineButton" />
This is our JS.
// this is "The Standard" and up to date way of doing
// it to make sure we don't update anything before the page has rendered.
$(document).ready(function(){
$( "#boldButton" ).on( "click", function() {
console.log("start");
var myTextAreavalue = "";
myTextAreavalue = $("textarea#my_textarea").val();
console.log(typeof myTextAreavalue);
var tag = $("input").val();
console.log(typeof tag);
var updatedText = ["<" + tag + ">" + myTextAreavalue + "</"+tag+">"];
$("#my_textarea").replaceWith(updatedText[0]);
console.log(updatedText);
});
});
From there I would maybe change out the event .on click to work when every button is clicked if this won't be used with other code elsewhere where there are lots of buttons. Then use an if else to see which button was clicked on and change the data on each one from in there. Happy to help! Have fun with JS! It's so powerful when you start looking into all of the wheels that are already put together for you!

How to clear a text field?

I want to place a cross button next to a text field, which, on clicking it, clears the value entered by the user. In other words, it empties the field. Please help..
And I also want to focus the field, but after some 2 or 3 seconds..
Like this:
$('#myButton').click( function () {
$('#myField').val('');
});
Or without jQuery
document.getElementById('myButton').onclick = function () {
document.getElementById('myField').value = '';
});
Try this,
$('#button').click(function(){
$('#inputBox').val('');
});
Have you tried anything at all? But this should do (edit after misread, see below):
$('#your_button').click(function() { $('#your_textbox').val(''); });
In Javascript:
document.getElementById('textField1').value = "";
Well, learn to break your tasks into smaller one and everything will become much easier. Here, for example, you have 2 tasks:
1) Place a "X" button near input. This is achieved by CSS and HTML. You HTML might look like:
Then you should align your image with you input
2) Actual erasing. In jQuery:
$("#x_button").click( function() {
$("#input_id").val( "" );
});
But this is real basics of web development, so you should really consider to read some kind of book on it.
You can do it with html5 value.
<input type="text" placeholder="Your text here">
Assuming your text field looks like this one :
<input type="text" id="myText"></input>
and your button looks like this one :
<input type="button" id="myButton"></input>
You just have to do this in javascript :
<script type="text/javascript">
var myButton = document.getElementById('myButton');
myButton.addEventListener("click", function () {
document.getElementById('myText').value = '';
}, false);
</script>
If you're using jQuery it's even easier :
<script type="text/javascript">
$('#myButton').click(function() {
$('#myText').val('');
});
</script>
here is a sample:
Html:
<input type="text" id="txtText" value="test value" />
<input type="button" id="btnClear" value="Clear" />
javascript:
$(document).ready(function () {
$("#btnClear").click(ClearText);
});
function ClearText() {
$("#txtText").val("");
}

Categories