javascript return URL onClick - javascript

I have a html form with a dropdown list of car models and a blank frame below that. I'd like to display a url related to the selected car in the frame when the submit button is pushed. I have it working and displays the current cars value in the frame, but I don't know how to insert and have JS return a URL value.
the JS goes like this: (and it may be completely wrong as I'm new to this stuff...)
function carFormSelect (form) {
var Car = form.selCar.value;
if (Car == 'Camry'){
document.querySelector('.carSelected').innerHTML = (Car);
}
HTML like this:
<select id="selCar" name="selCar">
<option value="Camry">Camry</option>
<option value="Corolla">Corolla</option>
</select>
I'm assuming I need the URL to be placed where (Car) is. I tried putting the url in quotes but didn't work. Any help would be greatly appreciated.
Thanks!

You can do that by using a JQuery/Ajax request.
You just need to get the value when the user clicks on the Select element and send it to another page that will have a iframe with the treated with the SRC that you want (in that case the car site)

Related

PHP dynamic id attribute of <a> element

I have a drop-down menu in a form with elements retrieved from a database. Something like this :
for($i=0;$i<count($resq);$i++){
print("<li><a class=\"dropdown-item\" href=\"#\" id=\"$i\">{$resq[$i][0]}</a></li>");
}
$resq being an array containing the result of the query (i used mysqli_fetch_all).
As you can see I tried to dynamically generate the id of the items(first item has id=0, second has id=1 and so on till the final value of $i) but I think this is not correct.
Previously, I had the following JS code(which worked) which I used to set the drop-down value to the one selected by the user and to set the value of a hidden input to that value.(I know the code isn't elegant but I just wanted to test the logic in the first place)
var x=document.getElementById('dropdownMenuButton1slct');//dropdown
var c1=document.getElementById("0");//i - categories(IDs of the dropdown elements)
var c2=document.getElementById('1');
var c3=document.getElementById('2');
var c4=document.getElementById('3');
var c5=document.getElementById('4');
var p=document.getElementById('iaval');//hidden input from form
function clic(z){
z.onclick=function () {
x.innerHTML=z.innerHTML;
p.value=x.innerHTML;
};
}
clic(c1);
clic(c2);
clic(c3);
clic(c4);
clic(c5);
But now the same method won't work. If you can, please suggest me a different way or something, I am kinda stuck. I can provide more info if this seems vague or something like that. Thanks.

Google Script - Form - live update for a text field

My client has a huge list of contacts.
I created a form with a scrolling list, in order to select a contact. The issue is that the scrolling list is too long.
Is there a way (and if so, how?) for my client to start typing the first letters of a contact name, so the 'field area' (or other) fills in automatically the correspondant contact name?
Thank you in advance for your help.
Kind regards,
You can load the select with this javascript:
function updateSelect(vA)
{
var select = document.getElementById("sel1");//or whatever you select id is
select.options.length = 0;
for(var i=0;i<vA.length;i++)
{
select.options[i] = new Option(vA[i],vA[i]);
}
}
The html select element:
<select id="sel1">
<option value="" selected></option>
</select>
I often load selects when the page loads with something like this:
$(function(){
google.script.run
.withSuccessHandler(updateSelect)
.getSelectOptions();//a gs function which passes an array to updateSelect via the success handler
});
That way I can use a spreadsheet to store the values that I want. In your case you may want to filter them alphabetically perhaps. And you might want to pass the getSelectOptioptions() function or whatever you call it a parameter to determine how to filter the list.

Why onchange event taking me to new page?

I am trying to populate a text field with the value of the select field.
So based on the selection the text field should change.
In this case, I am selecting First Name and Last name of the person and in the
option value="I have person email here"
Now, I am using onchange event on select element which calls the findemail() function.
Problem is I am getting the correct emails return but
it redirect me to another page and show me the value there.
Can anyone please help me?
CODE
function findemail(e)
{
document.getElementById('man-email-add').innerHTML=document.write(e.value);
}
HTML (I am using PHP to get all the values)
<select id="manager_detail" onchange="findemail(this.options[this.selectedIndex]);">
<?php
foreach ($data['display']['userMangers'] as $manager){
echo $manEmail = $manager['Email'];
echo "<option value='$manEmail'>".$manager['First_Name'].' '.$manager['Last_Name'].' ('.$manager['Position'].')'.'</option>';
}
?>
</select>
Redirect to new page to show the value:
It's because you're using document.write() after the page has loaded, which doesn't look necessary here anyway:
document.getElementById('man-email-add').innerHTML= e.value;
Does it redirect to new page or reloads the same page showing the email? I believe it's doing the later as document.write(e.value); writes that value to the page. So replace document.write(e.value); with e.value;
If man-email-add is an input field, use document.getElementById('man-email-add').value=e.value;

How do I refresh an html element?

I've tried searching for any possible solutions to my question but none of what I've seen so far works. Anyway, I'm using MVC 3 and I have a form called Add Event. On that page, I have a dropdownlist that contains a list of locations that the user can choose from. I have a link just below that dropdownlist that would allow a user to add a new location. Now, I have the textboxes, dropdowns, etc for creating a new location in a partial view which would appear below the dropdownlist when I click on the link.
Anyway, I need to refresh, just the dropdownlist so that when I add a new Location, it goes right on the list. What happens right now is after I click on save, the partial view hides itself and I still need to refresh the entire page to get the new location on the dropdown list which would then, remove everything I typed in on texboxes and dropdownlists on the same page.
How can I do this using javascript/ajax?
With jQuery you can reload only the element you want:
$('#menu').load("myServerScript.php #menu");
http://api.jquery.com/load/
This might help you..
var opt = document.createElement("option");
// Assign text and value to Option object
opt.text = Text;
opt.value = Value;
// Add an Option object to Drop Down
document.getElementById("YourDropDownID").options.add(opt,null);
this can be done with jQuery.
My way of doing it would be like this. Assuming that you have a form that looks something like this:
<form method="post" action="#">
<select id="myList" name="myList">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<input type="text" id="newValue" name="newValue" />
add new value
<input type="submit" value="Submit">
</form>
Where myList is dropdown you want to add a new value and refresh, newValue is the text field to receive the new values to be added to the dropdown (myList) and the link with id btn is the add button. You can add a jQuery that would look something like this:
<script type="text/javascript">
$(document).ready(function () {
$("#btn").click(function (event) {
event.preventDefault();
$.post("/home/addvalue", { value: $("#newValue").val() }, function (result) {
if (result != null) {
$("#myList").append("<option value='" + result.id + "' selected='selected'>" + result.text + "</option>");
}
});
});
});
</script>
What I'm is when you click on the link (btn) I collect the value (and just that value) from the text box and do POST (a form submit) to the server.
I'm guessing you're expecting the server to give some sort of answer that includes the newly inserted value's id.
If the server sends back that new id, I then append the the new result to list (and set it as the selected one)
On the server side you code could look something like this
[HttpPost]
public JsonResult AddValue(FormCollection collection)
{
//do database inser for the new value and get the id
var response = new Dictionary<string, object>();
response.Add("id", 3);//3 here represents that last id
response.Add("text", collection["value"]); //the value you sent for the new option
return Json(response);
}
you receive the the POST(ed) data and do save to the database. Once the value is saved and you have the new id save in into a dictionary that you'll then serialize and send back as json the javascript above.
This would update your form, so you when you actually hit submit myList value would be the new value.
Hope this helps (and if does, please accept the answer)

jQuery Mobile and MVC3 auto submit

The following code works perfectly if I take jQuery Mobile out of the question!
The form:
#using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" }))
{
#Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town")
}
The Javascript:
<script type="text/javascript">
$(function () {
$("#TownID").live('change', function () {
//$("#TownID").change(function () {
var actionUrl = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
$('#TheForm1').attr('action', actionUrl);
$('#TheForm1').submit();
});
});
</script>
But if I wrap jQuery Mobile around the site, then every time I submit the form, in my log only it tacks the ID field again and again to the end of the URL string. This only happens in my log, not in the browser. In the browser it still looks like it’s doing the right thing! E.g..
www.mysite.com/Home/SearchTown/2 the first time
www.mysite.com/Home/SearchTown/2/2 the second time
www.mysite.com/Home/SearchTown/2/2/2 the third time
But in the browser it still looks correct www.mysite.com/Home/SearchTown/2
Why is jQuery Mobile doing this?
This is most likely happening because each time you POST the form, it uses AJAX to load the response and the loaded page has repeated element IDs in it.
I'm guessing here, but based on what you described it sounds like your form posts back to a page with the same form markup on it. Each time your form post renders the next page you'll get another #TheForm1 added to your DOM (as jQuery Mobile keeps previously loaded pages in the DOM and simply swaps between active data-role="page" elements). Due to this behavior, once you have more than one #TheForm1 on the page, the selector $('#TheForm') will only ever return the first element in the DOM matching that ID- which will be the form which you posted the very first time. Thus, each time you you post, your code will use the action attribute of the form element you modified originally- which is why you see multiple values appended to the URL.
In jQuery Mobile it is almost always better to identify elements using a class name and the active page as the container, as you never know how many times an ID might be repeated in the DOM across multiple page changes. So, instead of using $('#TheForm1'), assign a class name and use that in conjunction with $.mobile.activePage: $('.Form1', $.mobile.activePage). (The same goes for your select box).
As an alternative, you can tell jQuery Mobile to not enhance your form by adding data-ajax="false" to the form tag. This will cause it to behave like a normal full page postback without any AJAX.
Edit
The point I am making in paragraph 3 is that you need to make sure you're always selecting the correct form element for the currently visible page, rather than unintentionally returning one which is hidden from view. The $.mobile.activePage global variable will give you the context of the currently visible page, and then a class-based selector (rather than Id-based) will ensure that the correct form element is retrieved in the change handler. Something like this:
<form class="town-form" action="#">
<select class="town-selector">
<option value="1">Town A</option>
<option value="2">Town B</option>
<option value="3">Town C</option>
</select>
</form>
<script type="text/javascript">
$(function () {
$(".town-selector").live('change', function () {
var form = $('.town-form', $.mobile.activePage);
var actionUrl = form.attr('action') + '/' + $(this).val();
form.attr('action', actionUrl);
alert('submitting to: ' + form.attr('action'));
form.submit();
});
});
</script>
because you are submitting the hole page and jQuery mobile does not fancy such thing, and after each POST it just appends the ID into the document.location... I have learned that in some mobile projects...
instead of this line $('#TheForm1').submit(); do something like this:
var url = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
$.post(url, $('#TheForm1').serialize(), function(data) {
// do something with data if you send back something...
// or just change page with jQuery Mobile API
});
return false;
Iv'e left this one up long enough and no one has an answer!

Categories