What I am doing is creating a simple html page in which there is a textbox. A user posts some input to that textbox such as
first last
first last
first last
first last
Imagine these are different names. What I would like to do is take the input in the textbox, and display it to the screen with the repeating names taken out, in alphabetical order, and with option tags added around them.
What I have
<div id="contentdisplay"></div>
<FORM action="" method="">
<p><LABEL for="content">Paste Code Here: </LABEL></p>
<p><textarea id="content" cols="80" rows="40"></textarea></p>
</FORM>
<script type="text/javascript">
$(document).ready(function() {
$('#content').change(function() {
var test = $('#content').val();
$("#contentdisplay").html(test);
});
});
</script>
Right now it takes the value from the textbox when the user clicks outside of it and spits it to the screen inside of the "contentdisplay" div. I'm stuck on the part where I split that user input into lines. I tried test.split('/n') and stuck it into a variable but that did not work out.
My Thoughts on Going About This
While looping, Split the form input by newline character, put each line into an array
Sort the array into alphabetical order. (Remove any empty lines or spaces before and after the lines during this part.)
I'm not sure about removing the doubles. In Java I used a set which automatically only allowed one of each entry to come in.
Using jquery's .html() cycle through array for display and add tags around
Wondering if anyone can enlighten me on my ideas and how I could go about this. Thank you!
Here is the near final version. Thanks to Erik for his help.
Here is what I did to get it where I wanted. Thanks for the help Erik.
<script type="text/javascript">
function process() {
entered = $('#content').val();
lines = entered.split(/\n/);
opttext = "";
lines = jQuery.unique(lines);
lines.sort();
for(var i in lines) {
opttext += "<option>" + lines[i] + "</option>";
}
$('#contentdisplay').html("<select>"+opttext+"</select>");
}
$(document).ready(function() {
$("#content").bind('change', process);
});
</script>
<div id="contentdisplay"></div>
<FORM id="myform" action="" method="">
<p><LABEL for="content">Paste Code Here and click anywhere on the screen: </LABEL></p>
<p><textarea id="content" cols="40" rows="10"></textarea></p>
</FORM>
Try this:
http://jsbin.com/okigi/3/edit
(edit: changed the form tag to a div so the example doesn't sumbit anywhere)
function process() {
entered = $('#content').val();
lines = entered.split(/\n/);
opttext = ""; for(var i in lines) {
opttext += "<option>" + lines[i] + "</option>";
}
$('#myform').append("<select>"+opttext+"</select>");
}
$(document).ready(function() {
$("#process").bind('click', process);
});
<FORM id="myform" action="" method="">
<p><LABEL for="content">Paste Code Here: </LABEL></p>
<p><textarea id="content" cols="40" rows="10"></textarea></p>
<button id="process">Go!</button>
</FORM>
This doesn't take out duplicates, or put them in alaphabetical order, but once you have the lines in the array "lines" you can figure out how to do those things on your own.
Related
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!
How can I set the ouput of this javascript function as the value for a hidden input on a html form?
document.write(states[i][1]);
works fine but I cannot get it to fill in the value with the code as shown below.
if (to == 'abbr'){
input = input.replace(/\w\S*/g, function(txt){return
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
for(i = 0; i < states.length; i++){
if(states[i][0] == input){
document.getElementById("sid").value = (states[i][1]);
}
}
}
}
</script>
<form action="we2.php" method="post">
<input type="text" id="sid" name="s1"/>
<input type="submit" value="Verify">
</form>
What is wrong with this code / what is the right way to do this?
Thanks!
This should do it.
HTML:
<input type="hidden" id="HiddenInput" />
JavaScript:
document.getElementById("HiddenInput").value = someFunction();
Have you checked if states[i][0] == input evaluates to true?
Write JavaScript code after html code end in your page or at the end of page.
I found a easier solution by just turning the entire function into a variable then the variable into the DOM:
var response = abbrState('<?php echo $_GET['state']; ?>', 'abbr');
document.getElementById("sid").value = response;
The following should work.
HTML:
<div style="display:none" id="example"></div>
Javascript:
function addTextNode(text) {
var newtext = document.createTextNode(text),
element = document.getElementById('example');
element.appendChild(newtext);
}
function yourFunctionDataHere(){
return 'test1234';
}
addTextNode(yourFunctionDataHere());
Just make sure, that the return type of your function is of type string. If you want to see the output simply remove the style="display:none" from the div in the above example.
Try it online on jsfiddle.
var textEntered = function() {
var input = document.userNameForm.userInput.value;
if(input) {
document.getElementById("resultText").innerHTML += input + "<br>";
}
}
This is what I have so far and this obviously just prints out the user inputs onto the screen in a list. But I want to somehow store all these user inputs from the form I have in my HTML, (maybe in an array?) and maybe assign each to a number and use Math.floor(Math.random()) to print out a random result. (I'm just making a little/random site where you put in the names of your friends and it returns and prints a random name from the names that you give it, if that makes sense).
I'm a beginner just so you know
function textEntered() {
var inputs = [];
$('form input').each((i,e)=>inputs.push(e.value));
if (inputs) {
document.getElementById("resultText").innerHTML += inputs[Math.floor(Math.random()*inputs.length)] + "<br>";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input value="Hello">
<input value="World">
<input value="from Stardust">
<button onclick="textEntered()">Submit Now!</button>
</form>
<div id="resultText">Submit it!
<br><br>
</div>
Is this essentially what you are looking for?
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >
I have two text boxes.What I want to do is while i Write something in one text box it should be copied to the other(i am able to do so).But my requirement is if i write anything else rather then a-z or A-Z or 0-9 then it should not copied to the second text box.
my html
<textarea name="source" id="src1" cols="150" rows="20" onkeyup="showRelated(event)">
<textarea name="source2" id="src2" cols="150" rows="20" >
my js
function showRelated(e) {
$("#src2").val($("#src1").val()) ;
}
Let me explain little bit more,Suppose i write LO^&1VE then in the second text box LOVE should be copied only.now if i go further like adding more LO^&1VE C**V then in the second text box LOVE CV should be appaer only.Can any one suggest me how to do this?
Use the regular expression [^a-zA-Z0-9] to check for or replace characters that are not alphanumeric
function showRelated(){
$("#src2").val( $("src1").val().replace(/[^a-zA-Z0-9]/g,"") );
}
Demo
function showRelated(e){
$("#src2").val( $("#src1").val().replace(/[^a-zA-Z0-9]/g,"") );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="src1" onkeyup="showRelated(event);"></textarea>
<textarea id="src2"></textarea>
Rather brutal way of doing it but here goes
function showRelated(e) {
var text=$("#src1").val().split("");
var pattern=/^[a-zA-Z0-9]*$/
var nStr='';
for (var i=0;i<text.length;i++) {
if (pattern.test(text[i])) {
nStr+=text[i];
}
}
$("#src2").val(nStr);
}
Basically this will check each char follows your criteria and then puts it in if it does.