Cannot set property in javascript form - javascript

I'm getting the following error:
Uncaught TypeError: Cannot set property 'sort' of undefined
I am getting the same error when trying to set other variables, target and search.
I can't see what I'm doing wrong. I'm intending setting variables which I can pass to a backend php script which will then submit a request in order to sort search results. This should be simple but I'm not sure what the problem is.
How do I set these variables so that I can submit the form?
HTML:
<div class="sort">
<form name="loop54" action="cart.php" target="_self" method="get">
<select id="sortBy">
<option value="Rel" selected="selected">Relevance</option>
<option value="PriceLoHi">Low to High</option>
<option value="PriceHiLo">High to Low</option>
<option value="A-Z">A-Z</option>
<option value="Z-A">Z-A</option>
</select>
</form>
</div>
JavaScript:
var selectmenu = document.getElementById("sortBy");
selectmenu.onchange=function() {
var selectedOption = this.options[this.selectedIndex];
document.loop54.target="_self";
document.loop54.sort = selectedOption;
// the line below refers to another form and works
document.loop54.search = document.ds_search.search.value;
document.loop54.submit();
}
I created a jsfiddle and it works there. Must be a problem elsewhere.

You have to set the name attribute for the <select id="sortBy"> element:
<select id="sortBy" name="sort">

If you want to send data to your PHP script using an HTML form, you should not manipulate the JavaScript object representing your HTML form.
The behaviour of your HTML form is this : if it contains fields with a name parameter (input tags with values, select tag with options selected), they will be sent in the HTTP Request, in an array where :
the name of the field is the entry
the value of the field is the value
So instead of doing what you do, you should :
add a input text field named "search" where your user will type his search query
add a name parameter to your select
Here's what it would look like :
var selectmenu = document.getElementById("sortBy");
selectmenu.onchange= function() {
// you can keep using JavaScript to submit your form, but select your form with its id :
document.getElementById("loop54").submit();
}
<div class="sort">
<form id="loop54" pname="loop54" action="cart.php" target="_self" method="get">
<select id="sortBy" name="sortBy">
<option value="Rel" selected="selected">Relevance</option>
<option value="PriceLoHi">Low to High</option>
<option value="PriceHiLo">High to Low</option>
<option value="A-Z">A-Z</option>
<option value="Z-A">Z-A</option>
</select>
<input type="text" name="search_ds"></input>
</form>
</div>
That way, you should end-up, server-side, with a $_GET variable containing an key/value for each of your fields : sortBy and search.

Related

How to add input value using jQuery

So I have a form that submits device,color and the problem(with the device) and it displays the correct price underneath nicely using jQuery but I can't figure out how to insert the jQuery result into the hidden input value so that it also sends the price to next page(checkout page) Thanks :)
<form method="POST" action="../action.php">
<select class="custom-select mr-sm-2" name="device" id="inlineFormCustomSelect">
<option value="Motorola Edge">Moto Edge</option>
<option value="Motorola Edge Plus">Moto Edge Plus</option>
</select>
<select class="custom-select mr-sm-2" name="color" id="inlineFormCustomSelect">
<option selected>Select Color..</option>
<option value="Solar Black">Solar Black</option>
<option value="Midnight Magneta">Midnight Magneta</option>
</select>
<select class="custom-select mr-sm-2" name="issue" id="inlineFormCustomSelect3">
<option data-price="£0.00" data-total="" selected>Select Problem..</option>
<option data-price="£40.00" data-total="£42.00" value="Screen Repair">Damaged Screen</option>
<option data-price="£15.00" data-total="£15.75" value="Battery Replacement">Battery Replacement</option>
<option data-price="£35.00" data-total="£36.75" value="Audio Repair">Faulty Audio</option>
<option data-price="£35.00" data-total="£36.75" value="Mic Repair">Faulty Microphone</option>
<option data-price="£35.00" data-total="£36.75" value="Cam Repair">Faulty Camera</option>
</select>
<p><i id="price"></i>+Additional Fees</p>
<p>Total:<span id="total"></span></p>
<script type="text/javascript" language="javascript">
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
$('#price').html(selected.data('price'));
$('#total').html(selected.data('total'));
}).change();
});
*//This is some code I tried below//*
$(document).ready(function(){
$('input[id="price"];').val(price);
});
</script>
<input type="hidden" id="price" name="price" value=''>
<button type="submit" name="submit">
In the case that you are trying to use the same values in an entirely different page. You should know that JS variables do not automatically save, you will lose them after refreshing the page or loading another page.
In order to save variables in the browser, you can use localStorage or localSession. In this particular case, I suggest localSession. localSession will delete the data when the browser is close or the cache is cleared.
Also, you could remove the semicolon ';' from $('input[id="price"];').val(price)
I do not suggest using localStorage or localSession for important forms, this requires back-end. You could use PHP, Node, Django, or any back-end for managing forms. But what you tried was ultimatly right, it's just that there was no variable set to retrive the data from. Hence, why the input could be left empty.
One way you can do this is to update the hidden field when you update the text field.
$(function(){
$('select').change(function(){
var selected = $(this).find('option:selected');
$('#price').html(selected.data('price'));
$('#total').html(selected.data('total'));
$('#hiddenPrice').val(selected.data('price'));
}).change();
});
HTML:
<input type="hidden" id="hiddenPrice" name="hiddenPrice" value="">
Notes:
In your question, the hidden input has the same Id as the text field. That's not valid HTML. So give your hidden input a different Id (such as id='hiddenPrice'). Also, be aware that hidden fields can still be modified by a user. You should validate the posted price in your server side code to verify it is the correct price.
Try these
$('select[name="issue"]').on('change', function() {
var issue = parseFloat($(this).children("option:selected").data('price'));
$('input[name="price"]').val(issue);
// or this one below
$('input[name="price"]').val(issue).trigger('change');
});
Also, try changing the id of your hidden input field and remove or extract this '£' from the data-price.

How to update url without losing input data

I have this option selector which updates url adding ?type=size, type depends on option selected. I use $_GET to then get the data from url.
The problem is, after entering value in inputs (name, price, etc) before, then on selection part the page refreshes and the input data I entered before is gone.
<label>Type</label>
<select name="type" onchange="location = this.value;">
<option>Select...</option>
<option value="?type=size">Size</option>
<option value="?type=weight">Weight</option>
<option value="?type=dimension">Dimension</option>
</select>
How can I fix this?

Redirecting page based on <select> value

I have a <select> tag on my site that when I change it submits the form and goes to the page in question where I can use the $_POST variable.
<form method='POST' action='myURL'>
<select onchange='this.form.submit();'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
</form>
This is fine and works as intended but if someone is on the page and refreshes it I don't want to have to have the warning for resubmitting the form.
So what I was trying to do is remove the form element and have something like this and I can use $_GET instead of $_POST.
<select onchange='window.location.href="myURL?var=this.value";'>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
</select>
However, this redirects to the page but the $_GET variable is literally this.value.
Is there another way of getting this to work or will I need to write an external piece of JS for this?
Note JS isn't my language, the snippets above are all being rendered via PHP
You've hardcoded the string - just do this instead:
<select onchange='window.location.href=("myURL?var=" + this.value);'>
I would suggest to you to avoid the use of inline-events as onchange and use the addEventListener() method instead to attach the change event.
So first give you select tag an identifier (id or class) then attach the event using this identifier like :
<select id="my-select">
Then in the JS part it could be attached like :
document.querySelector('#my-select').addEventListener('change', function(){
window.location.href = "myURL?var=" + this.value;
})
Or if you could use jQuery it will be :
$('#my-select').change(function(){
window.location.href = "myURL?var=" + $(this).val();
})

How to pragramatically change a dropdownlist to another field's value

I have a dropdownlist with a list of countries (all countries)
<select id="Country" onchange="country();">
<option id="3">Japan</option>
<option id="4">Canada</option>
<option id="5">France</option>
<option id="6">Peru</option>
</select>
I have the form in a modal that i want get country value from.
<input id="seachcountry" type="text" class="form-control" name="country">
I have written a JQuery line to get the value from the modal form to the page fields, everything works great but the country select fields are not changing the value.
$("#seachcountry").val($("#modalform").val()).trigger("chang‌e");
thank you for your suggestions!
This will work for you:
Just inject the value of the <input> to <select>.
I have created a snippet for you.
var Tval = $('#seachcountry').val();
$('#Country').val(Tval);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="Country" onchange="country();">
<option id="3">Japan</option>
<option id="4">Canada</option>
<option id="5">France</option>
<option id="6">Peru</option>
</select>
<input id="seachcountry" type="text" class="form-control" name="country" value="France">
Try this.
function country() {
$("#seachcountry").val($(this).val());
}
For changing value in any select you just need send exist value from this select. In your select options have only ids, but not have value attribute. So if you add value equal to id to change value in the your form to "France" need run following:
$("#selectId").val(5)
Instead of 5 you can obtain value from any other field or else.
If you want set your value to input field when changed in select, you need attach listener that will do all work. It will looks like this:
$("#selectId").on("change", function(){
$("#inputFieldId").val($(this).find(":selected").text());
})
This will set displayed value to select, to set real value just write instead $(this).find(":selected").text() this $(this).val()

jquery .serialize() is not incuding select list selected value in the serialized string

I want to serialize my div section using jquery .serialize(). I know that we can only serialize the form with this function. So for this i created the clone of my div section and append it in the newly created form element and than serialize. The other input fields are serializing but the select list value are not ( the selected value is not in the serialized string). I have created a JSFIDDLE :
http://jsfiddle.net/mj6Eg/1/
Html
<div id="serializethis">
<label>Quantity</label>
<select id="quantity" name="Quantity" size="1">
<option value="1">1</option>
<option value="5">5</option>
<option value="25">25</option>
<option value="50">50</option>
</select>
</div>
<button id="serialize">Serialize</button>​
JS
$("#serialize").click(function(){
var clone = $("#serializethis").clone();
var form = $("<form />").append(clone);
alert(form.serialize());
});​
What i am missing ?
When clone()-ing an element its selected value is lost. So your code won't work. The easiest solution would be keeping a <form> around the elements the whole time (unless you use HTML5 that's required anyway).
Another solution would be temporarily wrapping your elements in a form:
$("#serialize").click(function() {
var data = $("#serializethis").wrap('<form>').parent().serialize();
alert(data);
$("#serializethis").unwrap('form');
});

Categories