Concatenate search query and preset text to a search - javascript

Trying to re-create this search url
https://www.bing.com/search?q=site:https://www.imdb.com/title+Hakunamatata
but this code keeps doing the wrong thing. I want to concatenate the URL's. Not start a second query inline
<form method="get" action="http://www.bing.com/search">
<input type="text" name="q" size="25" maxlength="255" value="Hakunamatata" />
<input type="hidden" name="q1" value="site:www.imdb.com/title" />
<input type="submit" value="Bing Search" />
</form>
What I keep getting is URL's with & in them instead of +.
Is there some kind of Javascript or something that can combine the search terms into one search?

You'll need to use JavaScript to prepend 'site:www.imdb.com/title ' to the input's value when the submit event is fired.
form.addEventListener('submit', function(){
query.value = 'site:www.imdb.com/title ' + query.value;
})
<form method="get" action="http://www.bing.com/search" id="form">
<input type="text" name="q" size="25" maxlength="255" value="Hakunamatata" id="query"/>
<input type="submit" value="Bing Search" />
</form>

So, I had a brother rebuild the script in JS since I needed some complicated formatting tweaks. This is the end result
function submitForm(elm, url, values, query) {
let baseLoc = new URL(url);
let searchParams = new URLSearchParams(baseLoc.search);
for (const key in values) {
let inputBox = elm.parentElement.querySelector(
`input[name="${values[key]}"]`
);
searchParams.set(key, inputBox.value);
}
for (const key in query) {
searchParams.set(key, query[key]);
}
let newTab = window.open(`${url}?${searchParams.toString()}`);
if (!newTab)
alert(
'Pop-up Blocker is enabled! Please add this site to your exception list.'
);
}
<form onsubmit="event.preventDefault();">
<input type="text" value="" name="inputBox" />
<input type="text" value="" name="inputBox2" /><br />
<button
onclick="submitForm(this, 'https:/\/bing.com/search/',{'q':'inputBox'},{'test':'fish','123':'lookup'});"
class="btn btn-primary btn-sm"
>
btn2
</button>
<button
onclick="submitForm(this, 'https:/\/ebay.com/sch/',{'_nkw':'inputBox2'},{'asd':'123'});"
class="btn btn-primary btn-sm"
>
btn2
</button>
</form>
Optionally, use this if you want to have a button that submits all buttons at once.
function submitAllButtons(elm) {
let allButtons = elm.parentElement.querySelectorAll('button');
console.log(allButtons);
for (const button of allButtons) {
if (elm != button) button.click();
}
}
<button onclick="submitAllButtons(this)" class="btn btn-secondary btn-sm">
ALL
</button>

Related

Send form inside a while with java, ajax php

I have the following html code with a form
<form id="msg-form-nota">
<input type="hidden" name="id_nota" id="id_nota" value="${project.id}">
<label for="textfield">Calificación obtenida:</label>
<input type="text" name="nota" id="nota" class="form-control form-control-sm" value="${project.nota}" placeholder="Introducir calificación"><br>
<input type="submit" name="submit" id="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
and then I use the following javascript/ajax code to manage the form
$('#msg-form-nota').submit(e => {
e.preventDefault();
const postData = {
nota: $('#nota').val(),
id: $('#id_nota').val()
};
const url ='accion.php';
$.post(url, postData, (response) => {
toastr.success('añadidas!', 'Actualización ', {"hideDuration": 1500});
});
});
The problem that I detect and I don't know how to solve is that, for example, when using a while, 5 forms are created with the same name id, if I use the first form that loads me it works without problem, but if I use the rest, the form does not It works if not that all the content of the form goes to the url as if the method were a get, what can I do? Thank you
If you wanted to completely remove the ID attributes from your forms/elements you can quite easily simplify the entire code by using a FormData object with a reference to the form supplied as the single argument. The FormData object would collate the various input elements for use in the ajax request - thus negating the need to even try to identify the individual input elements explicitly.
document.querySelectorAll('[type="submit"]').forEach(input => input.addEventListener('click',e=>{
e.preventDefault();
/*
The `submit` button raised the event so the `event.target` refers to that button.
From the button we know the `form` is the parentNode - but you can use `closest`
to find the parent form.
*/
let fd = new FormData( e.target.parentNode );
fetch( 'accion.php', { method:'post', body:fd })
.then(r=>r.text())
.then(data=>{
console.log(data);
// call your success function.
toastr.success('añadidas!', 'Actualización ', {
"hideDuration": 1500
});
});
}))
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='123' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Geronimo' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='456' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Fred Flintsone' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
<form data-id='msg-form-nota'>
<input type='hidden' name='id_nota' value='789' />
<label>
Calificación obtenida:
<input type='text' name='nota' class='form-control form-control-sm' value='Spitfire' placeholder='Introducir calificación' />
</label>
<input type='submit' class='btn btn-success btn-sm' value='Añadir/modificar calificación' />
</form>
In the PHP script accion.php there will be 2 POST parameters sent by the fetch request. These two parameters have the same names as the form input elements. For instance:-
<?php
#accion.php
if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
$_POST['id_nota'],
$_POST['nota']
)){
// ... etc do whatever
}
?>
The issue, as your question implies, is because you're repeating the same id attribute multiple times as the HTML is generated in a loop.
The best way to fix this is to use common class attributes on the elements instead. Then you can target the specific instance which from the target property of the event which is raised and passed as an argument to the event handler function. You can also use DOM traversal methods to find the related elements and retrieve their values.
Also note that I wrapped the input within the label element. This removes the need for the for and id attributes on those elements, but retains the same functionality.
$('.msg-form-nota').on('submit', e => {
e.preventDefault();
let $form = $(e.target);
const postData = {
nota: $form.find('.nota').val(),
id: $form.find('.id_nota').val()
};
console.log(postData);
/* make your AJAX request here... */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_001">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_001" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_002">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_002" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>
<form class="msg-form-nota">
<input type="hidden" name="id_nota" class="id_nota" value="ID_003">
<label>
Calificación obtenida:
<input type="text" name="nota" class="nota form-control form-control-sm" value="Nota_003" placeholder="Introducir calificación">
</label>
<input type="submit" name="submit" class="btn btn-success btn-sm" value="Añadir/modificar calificación">
</form>

How to Combine 3 ID's when a button was clicked?

I've try this code
<p>Watch Series Online</p>
<input type="search" id="imdbseries" class="Search" name="" value=""
placeholder="IMDB ID">
<input type="search" id="season" class="Search" name="" value=""
placeholder="SEASON">
<input type="search" id="episode" class="Search" name="" value=""
placeholder="EPISODE">
<button id= "search" onclick="search()" >Watch Now</button>
<script>
function search() {
var imdbseries = document.getElementById('imdbseriesID','season#',episode#').value
window.location.href = "https://mysiteurl.com/tv.php?imdb="+ imdbseriesID + "&season=" + season# + "&episode=" + episode#;
}
</script>
but fail for 3 ID's..
I want that when I fill the box with
IMDB ID:tt9140554
SEASON:1
EPISODE:1
it should go to this EXSACT URL when the button was clicked.
https://mysiteurl.com/tv.php?imdb=tt9140554&season=1&episode=1
Your html
<p>Watch Series Online</p>
<input type="search" id="imdbseries" class="Search" name="" value=""
placeholder="IMDB ID">
<input type="search" id="season" class="Search" name="" value=""
placeholder="SEASON">
<input type="search" id="episode" class="Search" name="" value=""
placeholder="EPISODE">
<button id= "search" onclick="search()" >Watch Now</button>
Your script
function search() {
// The document.getElementById() takes one Id
let imdbseries = document.getElementById("imdbseries").value;
let season = document.getElementById("season").value;
let episode = document.getElementById("episode").value;
location.href = `https://mysiteurl.com/tv.php?imdb=${imdbseries}&season=${season}&episode=${episode}`
}
Here's the documentation for getElementById. As you can see it accepts only one argument.
An alternative is to use querySelector. (You can tidy up the markup a little by replacing putting the id values in the name attribute, and removing the ids altogether.) Then you can just target elements by their name attributes, grab the values, and then build a string.
(Note: at some point you may want to add some validation to check the input values are valid. For example, both season and episode should both be numbers.)
function search() {
const imdbseries = document.querySelector('[name="imdbseries"]').value;
const season = document.querySelector('[name="season"]').value;
const episode = document.querySelector('[name="episode"]').value;
console.log(`https://mysiteurl.com/tv.php?imdb=${imdbseries}&season=${season}&episode=${episode}`);
}
<input type="search" name="imdbseries" placeholder="IMDB ID" />
<input type="search" name="season" placeholder="SEASON" />
<input type="search" name="episode" placeholder="EPISODE" />
<button onclick="search()" >Watch Now</button>

Disable or enable only the current button

With a PHP for each cycle, I'm bringing articles from the database. In those articles, we have a comment section with a form. I want to check with jQuery if there is something written on the input before the comment is sent.
As the articles are being brought with a PHP cycle, I want to check only the article in which it is being written a comment, but jQuery checks all the articles and only enables or disables the first or top result being brought from the database. I want jQuery to check only on the article with a written comment.
Here's what I'm doing:
$(document).ready(function() {
$(".comment-submit").attr("disabled", true);
$("#group-post-comment-input").keyup(function() {
if ($(this).val().length != 0) {
$(".comment-submit").attr("disabled", false);
} else {
$(".comment-submit").attr("disabled", true);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" id="group-post-comment-input">
<button class="comment-submit">
Comment
</button>
</form>
As you can see on the snippet above, the buttons only get enabled when text is written on the first input only. I want the buttons to get enabled when text is written on their dependent input. If input 2 has text on it, enable button 2, and so on and so on.
How can I do that?
Since IDs must be unique to the DOM tree, you might consider using a class instead.
$(function() {
$(".group-post-comment-input").on('keyup', function() {
let $button = $(this).next('.comment-submit');
let disabled = !this.value;
$button.prop('disabled', disabled);
});
});
form {
margin: 0 0 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" class="group-post-comment-input">
<button class="comment-submit" disabled>Comment</button>
</form>
In my demonstration, I use jQuery's next() to traverse from the input on which the "keyup" event is fired to its associated button.
.next( [selector ] )
Get the immediately following sibling of each element in the set of matched elements. If a selector is provided, it retrieves the next sibling only if it matches that selector.
Another method is to traverse up to the form element with closest() and back down to the button with find(). This might be useful if you expect your HTML structure to change in a way that could break the next() traversal.
let $button = $(this).closest('form').find('.comment-submit');
I also recommend using prop() instead of attr() to enable and disable inputs.
ID must be unique,
but you need to use a name for sending information to your PHP server
document.querySelectorAll('button.comment-submit').forEach( bt => bt.disabled = true )
document.querySelectorAll('input[name="group-post-comment-input"]').forEach( inEl =>
inEl.oninput = e =>inEl.nextElementSibling.disabled = (inEl.value.trim().length === 0) )
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>
<br>
<form action="comment.php" method="POST">
<input autocomplete="off" type="text" placeholder="Add a comment" name="group-post-comment-input">
<button class="comment-submit"> Comment </button>
</form>

Issue with form validation Javascript

I am using Bootstrap and I have two identical forms. I am trying to add form submission to Google Search results and it works but when I include two of the same form it doesn't work because of the id being the same on both. How can I fix this? The ID needs to be the same because google looks for the "G". The reason I have two forms is because I have it displayed differently on mobile. Using media queries. Below is my code thanks.
<form name="globalSearch" class="navbar-form" role="search" form action="" onsubmit="return validateSearch()">
<div class="input-group add-on">
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:11;NB:1" />
<input type="hidden" name="ie" value="UTF-8" />
<input class="form-control" placeholder="Search entire site..." id="q" name="q" type="text">
<div class="input-group-btn">
<button class="btn btn-default btnSubmit" type="submit">
<i class="glyphicon glyphicon-search"></i>
</button>
</div>
</div>
</form>
function validateSearch() {
if (globalSearch.q.value.length == 0) {
document.getElementById("q").value = "Enter a Value";
document.getElementById("q").style.color = "red";
return false;
}
}
You probably want to change the placeholder, so the user don't have to delete the text than type in a query. Please view updated function.
function validateSearch() {
var q = document.getElementById('q');
if (q.value.length == 0) {
q.setAttribute('placeholder', 'Enter search term')
q.style.borderColor = "red";
return false;
}
}
Two elements can not share same ID.
Either use CSS styling to make different looks in mobile, either hide one of forms from webserver (PHP/etc) side either dont use getElementById - instead, use jQuery:
<form name="globalSearch" ... >
<input name="q" data-input-type="desktop" id="q">
..
</form>
<script>
function validateSearch() {
var field = $("input[data-input-type="desktop"]');
field.val("Enter value here...");
field.css("color","red");
}
</script>

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Categories