Change url based on drop down selection & text box value - javascript

I have a very simple form. I'm trying to redirect the page based on dropdown value selected and value entered in the text box.
My form looks like this:
http://devilscircuit.com/new/test.html
It just has a select box, a text box & a submit button. I'm trying to redirect the page once user clicks on submit button.
I'm not very well versed with JavaScript.
Can someone help me with it?
My current JavaScript looks something like this:
<script>
function setURL(){
var dt_value = document.getElementById("dt_id").value;
var dt_value2 = document.getElementById("dt_id2").value;
var sjdurl = "http://parshwatax.com/devilscircuit2/+dt_value2/index.php?
controller=search&search_query="+dt_value;
window.location.href=(sjdurl);
}
</script>
HTML Is below:
<h4 class="title2">Search Your Picture</h4>
<label>Please Select an Event </label>
<select style="width:205px; margin-left:68px;" id="dt_id2">
<option value="shop1">GURGAON'14</option>
<option value="shop2">NOIDA'13</option>
<option value="shop3">LUDHIANA'12</option>
</select> </br>
<label for="dt_id">Please enter your BIB number </label>
<input type="Text" id="dt_id" maxlength="25" size="23" style="margin: 5px 21px;"/> </br>
<input type='button' onclick='setURL()' value='SUBMIT' style="margin: 10px 208px;">
Please help me fix the redirect. THanks in advance.

You have a couple issues. One is your "sjdurl" concatenation has a syntax error. Should be
var sjdurl = "http://parshwatax.com/devilscircuit2/"+dt_value2+"/index.php?
controller=search&search_query="+dt_value;
Another issue is your retrieving the selected value of your "dt_id2" select field incorrectly. It should be like:
var dt_select = document.getElementById("dt_id2");
var dt_value2 = dt_select.options[dt_select.selectedIndex].value;

Related

Getting selected datalist option value, and innerHTML, without using jQuery

I have a situation where I want to let a user decide titles of books that I have on my db, using an input with a datalist (generated by php), after the user picked a title, he would click a submit button and the form would send the title in another file.
Everything worked fine but I didn't realized that I needed to send the ID of the book that the user selected, because there can be more than one book with the same title.
What I would like to have is the option of the datalist, that no longer has the title of the book inside its "value" attribute, but I want that title inside its innerHTML, so that the title gets displayed, while having the ID inside the "value" attribute. My problem is that if I do that, when the user clicks on the datalist option, the ID gets inside the text input, so the user may not know what book he choose.
summing up: I would like to have the datalist that displays the title, when an option is chosen, that title gets displayed in the text input, when I submit, the Id of the book gets sent in "FindBook.php" inside $_POST.
isIn() checks if the title is inside the array of titles, I would need to change that so that it can check if the ID is inside the array of IDs.
<form onsubmit="alert(document.getElementById('number').value);" action="FindBook.php" target="_blank" method="POST">
<input id="number" list="BooksById">
<input type="submit" value="Find">
</form>
<datalist id="BooksById">
<option value="1">Title1</option>
<option value="2">Title2</option>
<option value="3">Title3</option>
<option value="4">Title4</option>
</datalist>
<br>
<form onsubmit="alert(document.getElementById('string').value);" action="FindBook.php" target="_blank" method="POST">
<input id="string" list="booksByTitle">
<input type="submit" value="Find">
</form>
<datalist id="booksByTitle">
<option value="Title1"></option>
<option value="Title2"></option>
<option value="Title3"></option>
<option value="Title4"></option>
</datalist>
Since I don't understand jQuery I would really prefer a solution that doesn't imply that.
I think that in your case you must use a <select> tag instead of a <datalist> because you do not want the end user to enter new names (or yes?). However you can work with the data attributes like in the code below:
HTML:
<input list="titles" id="title-input" oninput="getBookId()">
<datalist id="titles">
<option data-value="5" value="A book name">
</datalist>
JavaScript:
function getBookId() {
var selectedTitle = document.getElementById("title-input").value;
var value2send = document.querySelector(`#titles option[value='${selectedTitle}']`).dataset.value; // Here now you have the book title id.
console.log("getBookId ~ value2send", value2send)
}
I hope it works for you.
Assuming you can provide distinct title values for each datalist option...
Add a dataset attribute, such as data-id, to your datalist option elements, containing the corresponding id, and add a hidden type input to your form. Then use the onsubmit event handler function to get the selected datalist option's dataset id value and assign it to the value of the hidden input:
function findBook(form) {
form.bookid.value = document.querySelector(`datalist option[value="${form.booktitle.value}"]`).dataset.id;
console.log(form.bookid.value);
return false;
}
<form onsubmit="return findBook(this)">
<input type="hidden" name="bookid">
<input name="booktitle" list="BooksById">
<input type="submit" value="Find">
</form>
<datalist id="BooksById">
<option data-id="1" value="Title1">
<option data-id="2" value="Title2">
<option data-id="3" value="Title3">
<option data-id="4" value="Title4">
</datalist>
Upon form submission, your PHP file will have the variables $_POST['bookid'] and $_POST['booktitle'] available.
Thanks for your suggestions. I prefer to use a datalist, instead of a select tag, because it looks more like a dropdown menu that works like a button. Using datalist allows me to find a book by a random word inside the title of it, while the select only finds the first word of an entry. I can also distinguish different books with the same name by another attribute that states if it's available or if it's taken.
I asked for no JQuery, i appreciate your help but I really don't understand them, even if it's cleaner to use them I would like a solution that doesn't use them.
I ended up using the solution CBroe suggested:
document.getElementById("bookTitle").addEventListener('input', function (evt) {
let data = this.value.split('');
document.getElementById("bookId").value = "";
if(isIn(data,'books')){
document.getElementById("bookId").value = data[0];
document.getElementById("bookTitle").value = data[1];
}
});
function checkForm(id, value, list){
if(isIn([document.getElementById(id).value,document.getElementById(value).value],list)){
alert("Book found");
return true;
}else{
alert("not found")
return false;
}
}
function isIn(value, list) {
switch (list) {
case 'books':
//this was generated by php in my code
if (value[0] == 1 && value[1] == "Title1"){
return true;
}
if (value[0] == 2 && value[1] == "Title2"){
return true;
}
return false;
break;
//I've cut out other cases
}
}
<form onsubmit="checkForm('bookId','bookTitle','books')" action="FindBook.php" target="_blank" method="POST">
<input id="bookTitle" list="booksByTitle" autocomplete="off">
<label>id:</label>
<input id="bookId" <!--type="hidden"-->
<input type="submit" value="Find">
</form>
<datalist id="booksByTitle">
<!-- value was generated by php in my code-->
<option value="1Title1">Title1</option>
<option value="2Title2">Title2</option>
</datalist>

Shopify - Debut Theme - Showing A Textbox if Certain Variant is Selected

I'm trying to show my "Embossing" textbox only when the "Style" dropdown option "Embossing" is selected. I've added the below code in my new template, product-customizable-template.liquid, which created the textbox but I want to hide it unless "Embossing" is selected.
<p class="line-item-property__field">
<label for="embossing">Embossing</label>
<input required class="required" id="embossing" type="text" name="properties[Embossing]">
</p>
"Style" Dropdown
The Style textbox has the following code:
<select class="single-option-selector single-option-selector-product-customizable-template product-form__input" id="SingleOptionSelector-0" data-index="option1">
<option value="None" selected="selected">None</option>
<option value="Embossing">Embossing</option>
<option value="Stamp">Stamp</option>
</select>
I am still working on the site, so it is not active right now.
Any help would be greatly appreciated, thank you!
You need to check on-page load and on change of select box using Javascript and you can add and remove custom code to form easily
You can check and try the below snippet for a better idea
// on change test for your condition
document.getElementById('SingleOptionSelector-0').addEventListener('change', function (e) {
_checkAndAppend();
});
// run on page load and check the for value and add if selected value meet condition
_checkAndAppend();
function _checkAndAppend() {
var item = document.getElementById('SingleOptionSelector-0');
var itemValue = document.getElementById('SingleOptionSelector-0').value;
if (itemValue == 'Embossing') {
var input = `<p class="line-item-property__field _embossing">
<label for="embossing">Embossing</label>
<input required class="required" id="embossing" type="text" name="properties[Embossing]">
</p> `;
item.parentNode.insertAdjacentHTML('beforeend',input);
} else {
if(document.querySelector('._embossing')){
document.querySelector('._embossing').remove();
}
}
}

Is there a way to disable a dropdown to users while still being able to submit a form with the disabled dropdown?

I have a dropdown that is disabled to the user. I want for the user to be able to press a button that changes the selected item to a different one. For example: from the 4th item in the dropdown to the 7th.
I've tried disabling the dropdown, but when I do that and submit the form, I get a PHP error saying Undefined index: id.
HTML:
<form>
<select id='id' name='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<button type='submit'>Submit</button>
</form>
JavaScript:
const dropdown = document.getElementById('dropdown');
const options = dropdown.options;
for (let i = 0; i < options.length; ++i) {
if (options[i].value === id) {
dropdown.selectedIndex = i;
break;
}
}
PHP (This line seems to be the one breaking):
$id = $_POST['id'];
It seems you haven't defined method and action in your form tag. By default, I think, the method is set to 'GET', so when checking 'POST' you'll run into your error.
Therefore, set "method='post'" (and best also an action, e.g. "action='/yourPageName.php') and see if that helps.
I figured out a solution that suits my needs. It was kind of simple. I just enabled the dropdown when I submitted the form, and instantly disabled it again.
id.removeAttribute('disabled');
const data = new FormData(document.getElementById('form'));
id.setAttribute('disabled', '');
request.send(data);
Thanks for the help though :)
A disabled input field will be ignored when you submit the form. I would suggest creating a hidden input field of name="id" if you want the user to view the dropdown but not select it.
<form>
<select id='id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10'>orange</option>
</select>
<input type="hidden" name='id' value="6" />
<button type='submit'>Submit</button>
</form>
You can make an hidden input with the id="id" and change the select id to "temp_id". Then, since you are making the request from javascript, you can just update the hidden field before making the request.
<select id='temp_id' autocomplete='none' disabled required>
<option value='2'>apple</option>
<option value='6'>banana</option>
<option value='10>orange</option>
</select>
<input type="hidden" name="id" id="id" value="">
Then, on your javascript, just before you make the request, run the code:
document.getElementById("id").value = document.getElementById("temp_id").value;

Displaying text with JavaScript from multiple conditions in form

In this question I would like to display some HTML text depending on a which combination of options is selected in a form. In this example for instance, I want to display some text if spelling is selected as a subcategory and 'greater-depth' (equivalent to an 'A' grade) is selected as the performance grade. I've developed this in Rails form_for but have shown the form as rendered in the browser.
<form class="new_english_grade" id="new_english_grade" action="/english_grades" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" /><input type="hidden" name="authenticity_token" value="VTtOS/86shuyQPW6/HfaduffmQiVXLiJb06IQp7+56LM8cD8KRnD3qLGbQBit4OuAIc92MYbFpPObR6ePYmY1g==" />
<div class="field">
<label for="english_grade_subcategory">Subcategory</label>
<select name="english_grade[subcategory]" id="english_grade_subcategory"><option value="Spelling">Spelling</option>
<option value="Reading">Reading</option>
<option value="Writing">Writing</option></select>
</div>
<div class="field">
<label for="english_grade_performance_grade">Performance grade</label>
<select name="english_grade[performance_grade]" id="english_grade_performance_grade"><option value="Not-started">Not-started</option>
<option value="Working-towards">Working-towards</option>
<option value="Working-at">Working-at</option>
<option value="Greater-depth">Greater-depth</option></select>
</div>
</form>
The text I'd like to display for instance is like:
<div id = "spelling_greater_depth">
This text is displayed only if 'spelling' and 'greater-depth' are selected in options
</div>
I have initially set my CSS to be:
#spelling_greater_depth
{
display: none;
}
My JavaScript is not really working yet so I have not included it but I was trying to implement it using this:
I think this might be enough to get you started https://jsfiddle.net/sxh0n7d1/37/
However it is very difficult to answer the question, can you clarify your question or give feedback to this answer if it is close?
$('select[name="english_grade"]').change(function () {
$('#spelling_working_at').css("display","none");
console.log($(this).val());
var fieldToShow = $(this).val();
$("#" + fieldToShow).css("display","block");
});

Checkboxes and <select> options don't persist in HTML 5 local storage

I'm coming to an unexpected conclusion regarding HTML5 local storage persistence and inputs. When I use < input type="text" > or < input type="textarea" >, then the data persists in local storage and on page load loads back into fields at the push of a button. But when I use type="radio" type="checkbox" or < select > options, none of those types of data persists.
Is this behavior by design, and I'm pushing against a brick wall trying to make it work, or is it my form element scripting that needs an overhaul? If it's by design, then you can answer yes. If not, you can check the details of my work below to give it a checkup and any feedback.
The user enters data into textarea fields like this:
<textarea name="s1frontTowerShockMtgOther" id="s1frontTowerShockMtgOther" cols="20" rows="4">
Then they tap on the save button coded like this:
<input type="button" value="Save Settings" onclick="persistData()" style="background-color:red; font-weight:bold">
The Javascript page does its magic:
function persistData()
{
if (html5StorageSupported())
{
var s1frontTowerShockMtgOther = document.form1["s1frontTowerShockMtgOther"].value;
var storageIndex = "practicelog.html.s1frontTowerShockMtgOther";
localStorage[storageIndex] = s1frontTowerShockMtgOther;
document.form1.numStored.value = determineNumberStoredElements();
}
}
When the user returns to the page, he taps on this button to populate the fields on that page:
<input class="loadButton" type="button" value="Load Data First" onclick="loadData()">
The Javascript is called:
function loadData()
{
document.form1["s1frontTowerShockMtgOther"].value = localStorage["practicelog.html.s1frontTowerShockMtgOther"];
}
That's it. The following does not work:
<select size="1" name="frontTowerMtgShock" id="frontTowerMtgShock">
<option value="">Tap to choose</option>
<option value="0 spacers">3-outer</option>
<option value="1 spacer">2-middle</option>
<option value="2 spacers">1-inner</option>
<option value="other">See notes</option>
</select>
The following type="checkbox" does not work. It doesn't work if "checkbox" was replaced by "radio" either:
<input type="checkbox" name="s1frontTowerMtgShock3" id="s1frontTowerMtgShock3" value="3-outer">
I am doing this project for the iPhone with HTML, CSS, and Javascript through PhoneGap 1.0 integration.
The following works fine for me:
function persistData()
{
var s1frontTowerShockMtgOther = document.form1["s1frontTowerShockMtgOther"].value;
var storageIndex = "practicelog.html.s1frontTowerShockMtgOther";
localStorage[storageIndex] = s1frontTowerShockMtgOther;
storageIndex = "practicelog.html.frontTowerMtgShock";
var frontTowerMtgShock = document.form1["frontTowerMtgShock"].value;
localStorage[storageIndex] = frontTowerMtgShock;
}
function loadData()
{
alert(localStorage["practicelog.html.frontTowerMtgShock"]);
document.form1["frontTowerMtgShock"].value = localStorage["practicelog.html.frontTowerMtgShock"];
}
Have you double checked your storage keys when setting and retrieving?

Categories

Resources