TL;DR (Short synopsis):
I have recreated the admin "Add" button in my own project. However, when I hit "save" on the parent form, it is not recognizing the new select element.
Whole Story:
I have that functionality working in my own project... almost. I need help figuring out the last step. As it is now, I have a "+" button, I click it, a popup shows up, I add a new object, hit save, popup closes and that new item is now in my select box and selected - just like the admin page. However, when I hit save on this parent form, I get the error that I've selected an item not in the list. Of course, since the page has reloaded, my new item is part of the list and I just hit save again and it works. Of course, I need it to save on the first time!
The basic setup is my Parent model is called System and the foreign key model is called Zone. The Zone model lists how many zones a system has (1 zone,2 zones,10 zones, etc...)
OK, some code:
The "Add" link in the template of the parent form:
Add
In my New_Zone view, after saving the new zone, I check if the popup GET variable is 1, if so, return a javascript function. Here's the view:
...
if form.is_valid():
f = form.save(commit=False)
pk_value = f.numOfZones
form.save()
obj = Zone_Info.objects.get(numOfZones=pk_value)
if isPopup == "1":
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
...
And here is my Javascript (largely copied from the admin javascript:
function html_unescape(text) {
// Unescape a string that was escaped using django.utils.html.escape.
text = text.replace(/</g, '<');
text = text.replace(/>/g, '>');
text = text.replace(/"/g, '"');
text = text.replace(/'/g, "'");
text = text.replace(/&/g, '&');
return text;
}
function windowname_to_id(text) {
text = text.replace(/__dot__/g, '.');
text = text.replace(/__dash__/g, '-');
return text;
}
function showAddPopup(triggeringLink, pWin) {
var name = triggeringLink.id.replace(/^add_/, '');
href = triggeringLink.href;
var win = window.open(href, name, 'height=500,width=800,resizable=yes,scrollbars=yes');
win.focus();
return false;
}
function closeAddPopup(win, newID, newRepr) {
newID = html_unescape(newID);
newRepr = html_unescape(newRepr);
var name = windowname_to_id(win.name);
var elem = document.getElementById(name);
if (elem) {
if (elem.nodeName == 'SELECT') {
var o = new Option(newRepr, newID);
elem.options[elem.options.length] = o;
o.selected = true;
} else if (elem.nodeName == 'INPUT') {
if (elem.className.indexOf('vManyToManyRawIdAdminField') != -1 && elem.value) {
elem.value += ',' + newID;
} else {
elem.value = newID;
}
}
} else {
var toId = name + "_to";
elem = document.getElementById(toId);
var o = new Option(newRepr, newID);
SelectBox.add_to_cache(toId, o);
SelectBox.redisplay(toId);
}
win.close();
}
I took a look at this question and it seems that I am doing precisely the same thing.
Any ideas on how to get that last step of getting the form to recognize the new select element?
Thanks!
I Figured it Out
The problem was what I was passing to my closeAddPopup javascript function. Essentially, I was passing garbage values.
Here's what I originally had in my New_Zone view (which didn't work):
...
if form.is_valid():
f = form.save(commit=False)
pk_value = f.numOfZones
form.save()
obj = Zone_Info.objects.get(numOfZones=pk_value)
if isPopup == "1":
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
...
It's a pretty stupid mistake on my part (clearly it's late). I was assigning f to the field numOfZones which I thought was the pk and sending that to the script.
Now, the working view looks like this:
if form.is_valid():
obj = form.save()
pk_value = obj.pk
if "_popup" in request.REQUEST:
return HttpResponse('<script>opener.closeAddPopup(window, "%s", "%s");</script>' % (escape(pk_value), escape(obj)))
Anyway... thanks to... well, Stackoverflow. I don't think I would have solved the problem without posting the question and rereading my code on stackoverflow.
Related
I have this keyboard site launcher script, which I copied from some place years ago and it works fine as is. I want to enhance it by adding a cascading keypress launch for some of the keys. Here is my code:
<html><head>
<script language="JavaScript">
<!-- Begin
var key = new Array();
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "https://slashdot.org";
key['y'] = "http://www.yahoo.com";
function getKey(keyStroke) {
isNetscape=(document.layers);
eventChooser = (isNetscape) ? keyStroke.which : event.keyCode;
which = String.fromCharCode(eventChooser).toLowerCase();
// alert('['+which+'] key \n has been stroke');
runUrl(which);
}
function runUrl(which) {
for (var i in key)
if (which == i) {window.location = key[i];}
}
document.onkeypress = getKey;
// End -->
</script></head>
<body>
Make a selection<br>
<br>
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "https://slashdot.org";
key['y'] = "http://www.yahoo.com";
<br>
<br>
<!-- I solemnly swear this page is coded with vi or notepad.exe depending on the OS being used -->
</body>
</html>
Now, I want to modify the action for pressing the letter "s" to launch a submenu of sorts and ask me to select if I want to go to "Slashdot" or Spotify" for instance. like if I press an "s" second time, it goes to slashdot and if I press "f" for instance, it goes to spotify.
My problem is, I have never programmed in Javascript other than copying and pasting code and changing string values in the code, like here, changing the pressed keys and site URLs.
Any pointers, regarding how to start modifying this code, are greatly appreciated.
to be honest, the code provided is a bit outdated but I keep it so you can see the necessary changes that I made for the menu to be added and to implement the feature it's just a sketch but I will do the job I think from here you can expand, hope this puts you in the right direction
let isopenMenu = true;
const menu = document.getElementById("menu");
function toggleMenu() {
isopenMenu = !isopenMenu;
menu.style.display = isopenMenu ? "block" : "none";
}
var key = new Array();
key["a"] = "https://www.arstechnica.com";
key["g"] = "https://www.google.com";
key["s"] = "https://slashdot.org";
key["y"] = "http://www.yahoo.com";
key["b"] = "http://www.stackoverflow.com";
key["c"] = "http://www.test.com";
const menuSite = ["b", "c", "s"];
function getKey(keyStroke) {
isNetscape = document.layers;
eventChooser = isNetscape ? keyStroke.which : event.keyCode;
which = String.fromCharCode(eventChooser).toLowerCase();
runUrl(which);
}
function runUrl(which) {
for (var i in key)
if (which == i) {
if (which === "s") {
return toggleMenu();
}
if (!isopenMenu && menuSite.includes(which)) {
return;
}
window.location = key[i];
}
}
document.onkeypress = getKey;
window.addEventListener("load", toggleMenu);
<html><head>
<script language="JavaScript">
</script></head>
<body>
Make a selection<br>
<br>
key['a'] = "https://www.arstechnica.com";
key['g'] = "https://www.google.com";
key['s'] = "to toggel menu
key['y'] = "http://www.yahoo.com";
<br>
<br>
<ul id="menu">
<li>key['b'] = "http://www.stackoverflow.com";</li>
<li>key['c'] = "http://www.test.com</li>
</ul>
</body>
</html>
Indeed the code you've provided seems a bit dusted. There's some stuff that isn't done in that way nowadays. Notepad is an editor I still occassionally use though.
Since you've mentioned that you never really used JavaScript it's a bit hard to give you advice. You can do things way more elegant and even improve the look - but I'd say this would just confuse you even more. So let's work on something based on your code.
At the moment the keys and the corresponding targets are stored in an object (yeah, it's an object not an array). We can use a second object - let' say subKey - to store the additional targets upon pressing s.
var key = {};
key.a = "https://www.arstechnica.com";
key.g = "https://www.google.com";
key.s = "subMenu";
key.y = "http://www.yahoo.com";
var subKey = {};
subKey.a = "https://www.stackoverflow.com";
subKey.g = "https://www.startpage.com";
subKey.s = "goBack";
As you can see I've reserved the key s to go to the sub menu and inside the sub menu this button is used to go back to the main menu.
Now instead of hardcoding what the user gets to see on screen, we can iterate over those objects and use the information from there. To do this we need to reserve a html element - I've chosen an empty <div> which acts as some sort of container. As we iterate over the object we construct a string with the keys and it's associated targets and ultimately assign this this to the div's .innerHTML property.
let container = document.getElementById("container");
container.innerHTML = "Make a selection<br><br>";
for (var i in obj) {
container.innerHTML += "key['" + i + "'] = " + obj[i] + "<br>";
}
As the procedure is the same for both objects we just need to wrap it inside a function and pass it a reference to the desired object.
Your runUrl function needs to be modified a bit to take care of the additional options. This is best done with a simple if-else construct. So in pseudo-code:
if choice is subMenu open sub menu
if choice is goBack open main menu
if it's none of the above open a link
If we put everything together, your example looks a little bit like this:
(Just click on 'Run code snippet' and make sure to click somewhere inside the window so it'll have key focus)
<html>
<head>
</head>
<body>
<div id="container">
</div>
</body>
<script type="text/javascript">
var key = {};
key.a = "https://www.arstechnica.com";
key.g = "https://www.google.com";
key.s = "subMenu";
key.y = "http://www.yahoo.com";
var subKey = {};
subKey.a = "https://www.stackoverflow.com";
subKey.g = "https://www.startpage.com";
subKey.s = "goBack";
var currentObj = key;
function getKey(event) {
let which = String.fromCharCode(event.keyCode).toLowerCase();
runUrl(which)
}
function runUrl(which) {
for (var i in currentObj) {
if (which == i) {
if (currentObj[i] != "subMenu") {
if (currentObj[i] != "goBack") {
window.location = currentObj[i];
} else {
populateMenu(key);
}
} else {
populateMenu(subKey);
}
}
}
}
function populateMenu(obj) {
currentObj = obj;
let container = document.getElementById("container");
container.innerHTML = "Make a selection<br><br>";
for (var i in obj) {
container.innerHTML += "key['" + i + "'] = " + obj[i] + "<br>";
}
}
populateMenu(key);
document.onkeypress = getKey;
</script>
</html>
It looks like could achieve this with arbitrary list of sites. If so, you could handle this a little more generically by providing a list of sites and filtering the sites based on keystrokes.
If so, you can achieve it with the following:
const sites = [
'https://www.arstechnica.com',
'https://www.google.com',
'https://mail.google.com',
'https://slashdot.org',
'https://spotify.com',
'http://www.yahoo.com',
];
let matches = sites;
document.getElementById('keys').addEventListener('keyup', event => {
const keys = event.target.value.toLowerCase().split('');
matches = sites
.map(site => ({ site, stripped: site.replace(/^https?:\/\/(www\.)?/i, '')})) // strip out https://wwww. prefix
.filter(site => isMatch(site.stripped, keys))
.map(site => site.site);
if (event.keyCode === 13) {
if (matches.length === 0) {
alert('No matches');
} else if (matches.length === 1) {
alert(`launching ${matches[0]}`);
} else {
alert('More than one match found');
}
matches = sites;
}
document.getElementById('matches').textContent = matches.join(', ');
});
// find sites matching keys
function isMatch(site, keys) {
if (keys.length === 0) return true;
if (site.indexOf(keys[0]) !== 0) return false;
let startIndex = 1;
for (let i = 1; i < keys.length; i++) {
let index = site.indexOf(keys[i], startIndex);
if (index === -1) return false;
startIndex = index + 1;
}
return true;
}
document.getElementById('matches').textContent = matches.join(', ');
<div>Keys: <input type="text" id="keys" autocomplete="off" /> press Enter to launch.</div>
<p>Matches: <span id="matches" /></p>
The key parts to this are:
Define a list of sites you want to handle
Ignore the the https://wwww prefixes which is achieved with site.replace(/^https?:\/\/(www\.)?/i, '')
Implement filter logic (in this case it is the isMatch method) which tries to match multiple keystrokes
For demonstration purposes, I've wired keyup to an input field instead of document so that you can see it in action, and the action is triggered with the enter/return key.
Hi i have many forms inside multiple pages all of them the with the same id (success message) after submitted and same class names when i'm sending the form which e.g inside home page i put element selector through id with Page PATH with match regex something like that \/(en|es)\/ it works good without problem ... but when i'm going to page www.something.com/send-something/233?search=profile the form submitted through old id which was for home page i tried to inject custom javascript something like :
function() {
var els = document.querySelectorAll('#sendReqSurgyForm1');
for (var i = 0; i < els.length; i += 1) {
if (els[i] === {{Page URL}}) {
return i;
}
}
return '(nothing sent)';
}
with adding matching Page URL with match regex something like that to https:\/\/www\.something\.com\/(ar|en)\/send-something\/[0-9]+\?source=[a-zA-Z]+\_?[a-zA-Z]+
to matching the url: www.something.com/send-something/233?search=profile
the trigger always works with home page but trigger which located in www.something.com/send-something/233?search=profile not success and the result of javascript always returns nothing sent .. please help to fix this problem
Hi the Answer is SPA Angular using SPA so it can be multiple form with the same component so i solved this problem through setting id for every form with different urls
for example if you have multiple forms in angular inside multiple routing page as i explained in the main topic question .. to fix this problem you can setting id for every form submissions through js by setting new id for every form submission by setting Attribute for id based different urls.
main_id = exampleForm
function(){
var ids = document.getElementById("exampleForm");//main id
var current_url = window.location.href;//current url of visitor
var dir_match = location.pathname+location.search;//the path of website after .com
var send_req = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en]n/)+'/surgery-request/'+dir_match.match(/[0-9]+/)+'?source=profile';//link1 which have form1
var send_req2 = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en]n/)+'/surgery-request/'+dir_match.match(/[0-9]+/)+'?source=profile2';//link2 which have form2
var home_url = 'https://www.example.com/'+dir_match.match(/[ar][r]|[en][n]/)+'/';//link3 which have form3
if(current_url == send_req){
/* if current_url equal to link1 set new id e.g = `forms_req_surgery` */
last_send_req = ids.setAttribute("id", "forms_req_surgery");
var elm = document.getElementById('forms_req_surgery');
var last_var = elm.id;/* get the name of id */
return last_var; // return the name of id after changed set
}else if(current_url == home_url){
last_home_url = ids.setAttribute("id", "home_req");
var elm2 = document.getElementById('home_req');
var last2_var = elm2.id;
return last2_var;
}else if(current_url == send_req2){
last_send_req2 = ids.setAttribute("id", "forms_req_surgery2");
var elm3 = document.getElementById('forms_req_surgery2');
var last3_var = elm3.id;
return last3_var;
}
}
i'm creating a form of inscription and i want to get info from a first page to show in a second one. I've tried to use local storage, but it doesn't work.
I've tried to test in the same page, which works, but when i try it with the localstorage, it doesn't work, and when i click on submit it reloads the page and nothing happens
Here is the code for the first page:
function rform()
{
document.getElemeentByName('insc').reset;
}
function client()
{
var sexe=document.getElemeentByName('gender');
var userT=document.getElementById('choice').selectedIndex;
var name = document.getEelementById('name').value;
localStorage.setItem('name',name)
if (userT[1] || userT[2] &&sexe[0].checked )
{
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice)
else
{
var res = document.getElementById('choice').value + 'e';
localStorage.setItem('choice',choice)
}
return false;
}
And the second page:
<span id="result"></span>
<script type="text/javascript">
document.getElementById("result").innerHTML= 'welcome '
+localStorage.getItem('name')+ ' you are '
+localStorage.getItem('choice');
</script>`
I get nothing in the second page, but expect to get a welcome message with the name and the user type
var choice = document.getElementById('choice').value;
localStorage.setItem('choice','choice')
This isn't setting the value of Choice into localStorage, this is simple setting the value of localStorage named Choice to the string "Choice".
Should be;
var choice = document.getElementById('choice').value;
localStorage.setItem('choice',choice);
I am wondering how to take the information from a parsed query string and use it to display on the top of my page. Ignore the window.alert part of the code, I was just using that to verify that the function worked.
For example: If the user had choices of Spring, Summer, Winter, and Fall, whichever they chose would display a a header on the next page. So if (seasonArray[i]) = Fall, I want to transfer that information into the form and display it as a element. I'm sure this is easily done, but I can't figure it out. Thanks, in advance.
function seasonDisplay() {
var seasonVariable = location.search;
seasonVariable = seasonVariable.substring(1, seasonVariable.length);
while (seasonVariable.indexOf("+") != -1) {
seasonVariable = seasonVariable.replace("+", " ");
}
seasonVariable = unescape(seasonVariable);
var seasonArray = seasonVariable.split("&");
for (var i = 0; i < seasonArray.length; ++i) {
window.alert(seasonArray[i]);
}
if (window != top)
top.location.href = location.href
}
<h1 id="DynamicHeader"></h1>
Replace the alert line with:
document.getElementById("DynamicHeader").insertAdjacentHTML('beforeend',seasonArray[i]);
I manage a website for an organization that has separate chapter sites. There is a membership signup form that is on the main website that each chapter links to. On the form there is a dropdown box that allows a person to choose the chapter they want to join. What I would like to do is have each chapter website use a specific link to the form that will preselect their chapter from the dropdown box.
After searching the web, I found that I will probably need to use a Javascript function to utilize a Query String. With all my searching, I still can't figure out the exact code to use. The page is a basic HTML page...no php and it is hosted on a linux server.
Any help would be greatly appreciated.
If you format your url like this:
www.myorg.com?chapter=1
You could add this script to your html head:
function getparam(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}
function loadform()
{
var list = document.getElementById("mychapterdropdown");
var chapter = getparam("chapter");
if (chapter>=0 && chapter < list.options.length)
{
list.selectedIndex = chapter;
}
}
The in your html body tag:
<body onload="loadform();" >
Could probably add more validation checks but that's the general idea.
It sounds like what you are looking for are GET or POST requests. For instance, if your user selects "Chapter A" from your form and hits select, you can allow redirects from another site (for instance http://www.yoursite.com/form.html?chapter=A) to allow Chapter A to be preselected. In Javascript this is done by
var chapter="";
var queryString = location.search.substring(1);
if ( queryString.length > 0 ) {
var getdata = queryString.split("&");
var keyvalues;
for(var i=0; i < getdata.length; i++){
keyvalues = getdata.split("=");
}
} else {
chapter = "Not Found";
}
document.getElementById( "ChapterID").value = keyvalues['chapter'];
This is untested, so don't hold me to it :).
maybe something using parse_url
$params = parse_url()
$query = $params['query'];
$query_pairs = explode('&',$query);
$key_val = array();
foreach($query_pairs as $key => $val){
$key_val[$key] = $val;
}
http://www.php.net/manual/en/function.parse-url.php
You would probably have to use an dynamic ajax content. Use the following javascript to read the querystring, then load the html file in that div using this javascript.