I am working on a bootstrap environnement with classic asp.
I have a dynamically generated input fields
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
There can be up to 100 dynamically generated fields on one page.
The basics are that i should fill the field montantafacturer_<%=irs("INSPECTIONID")%> with a numeric value and click on add to insert value in the database in a postback method
I am wondering if i can insert a javascript code to check if my field is filled rather than getting the field empty error from postback response... to gain time
ie :
<input type="number" size="5" name="montantafacturer_<%=irs("INSPECTIONID")%>">
<button onclick="**IF montantafacturer_<%=irs("INSPECTIONID")%>" IS NOT EMPTY THEN** _EVENTSPARAM('events_ajouteralafacturation','<%=irs("INSPECTIONID")%>');">add</button>
I wonder if this can be done via inline javascript.
Please advise how.
iid = irs("INSPECTIONID")
if iid <> "" then %>
<input type="number" size="5" name="montantafacturer_<%=iid%>">
<button onclick="_EVENTSPARAM('events_ajouteralafacturation','<%=iid%>');">add</button>
<$ end if %>
That way if your recordset is empty, no HTML is output. If you move the IF/THEN to just before the Button tag, then no button will be created for an empty value.
First of all, welcome to StackOverflow
Secondly ... It's been a very long while when I stopped using Classic ASP (more than 15 years ago), it's nice to see that he still has a small place out there :)
Last, but not the least... your question
as you have input and buttons, I'm sure you have a for loop and outside I will assume you have a <form> tag wrapping all inputs and buttons
To accomplish what you're trying to do, and making use of better code techniques, I would most likely end up with something as (and assuming that you can use jQuery to lift a bit of the javascript... let me know if you can't, and I'll re-write without it)
<form action="/yourpage.asp" method="POST">
<table class="table">
<tbody>
<% For ... %>
<tr class="tr-<%=irs("INSPECTIONID")%>">
<td>
<input
type="number"
size="5"
id="montantafacturer_<%=irs("INSPECTIONID")%>"
name="montantafacturer_<%=irs("INSPECTIONID")%>">
</td>
<td>
<button
class="btn"
data-event="events_ajouteralafacturation"
data-input="<%=irs("INSPECTIONID")%>"
>add</button>
</td>
</tr>
<% Next %>
</tbody>
</table>
</form>
<script>
$(function() {
// for every button with class "btn", fire "onButtonClick" fn upon click
$(".btn").on("click", onButtonClick);
});
function onButtonClick(evt) {
evt.preventDefault();
var btn = $(evt.currentTarget); // the clicked button
var btnEvent = btn.data("event");
var btnInput = btn.data("input");
// your logic
var input = $("#montantafacturer_" + btnInput).val();
if(input.length === 0) {
// show the error in any way you prefer
return;
}
// if we reach here, we have data in the input
_EVENTSPARAM(btnEvent, btnInput);
// you can now fire some code to submit the form
// or just this value, or even disable the button while it
// is being used to send the data (prevent double click), etc.
}
</script>
the <tr class="tr-<%=irs("INSPECTIONID")%>"> was a technique that I used back then so I could add a class that would mark that row with another color, to give some feedback to the user that something was happening with that row data, for example
$(".tr-" + btnInput).addClass("updating");
I've also added id to the input to use $("#...") instead of search by name
Small rant on using JS inline
Why would you ever use inline JS? It really isn't practical or readable - highly recommend moving that into an external source.
How to use JS inline (pls don't)
But if there is absolutely no way around for you, you can always just throw all your normal JS code inside an inline event like onclick.
<button onclick="
// this makes me sad
const allInputs = document.querySelectorAll('[name^=montantafacturer_]');
allInputs.forEach(input => {
if (input.value.length > 0 && !isNaN(input.value)) {
// number
} else {
// empty / Not a Number
}
});
">
add
</button>
This is about what you are looking for.
Mentions
Really, don't use inline JS
As pointed out by another user - you may want to use the HTML property required
Related
I have multiple reason codes (For ex: RC1, RC2...). For each of these reason codes, I want to give the user a text box in which they can enter some comments. Also give them the option of adding multiple text boxes for each reason code.
To allow the user to add a dynamic text box, I have a button which allows the user to do so. If there was only one reason code, I can easily just just append a text box to the pre-existing text box using jquery (Using something like this: JQuery adding class to cloned element).
However since I have multiple reason codes(over 200) it doesnt make sense of having button for each reason code in Jquery. Is there a way for me to search by a basic identifier.
I have pasted the contents of the HTML file generated by my JSP file.
<div id="Reasoncode1">
<div id="inputTextBox_Reasoncode1">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode1">
+</button>
</div>
</div>
<p>
Reason code2
</p>
<div id="Reasoncode2">
<div id="inputTextBox_Reasoncode2">
<input type="text" placeholder="Add some text"/><button class="button_Reasoncode2">
+</button>
</div>
</div>
My Jquery attempt is:
$(".button_Reasoncode1").click(function() {
$('#Reasoncode1').clone().insertAfter('#inputTextBox_Reasoncode1');
});
$(".button_Reasoncode2").click(function() {
$('#Reasoncode2').clone().insertAfter('#inputTextBox_Reasoncode2');
});
I dont want to do this for each and every reason code, i was wondering if there is a better approach to this.
My JSFiddle: https://jsfiddle.net/mvp71L61/
Assuming all buttons are statically added to the DOM,
$("button[class*='button_Reasoncode']").click(function() {
var rCode = $(this).attr('class').match(/\d+/g)[0];
$("div[id='Reasoncode'+rcode]").clone().insertAfter("input[id='inputTextBox_Reasoncode'+rcode]");
});
I apologize if this question has been poorly worded. The reason I'm asking here is because I didn't know how to Google it properly.
Basically, I want the client to be able to specify a number (they could type the number in a textbox or there could be a series of numbers in a drop-down box or even radio buttons, i'm very flexible with this) that determines how many set of questions the form will display.
To put it into context to make it hopefully easier to understand:
-The form is for booking tickets
-If the client chose '1' at the start, it would mean one ticket so only one set of questions would be visible
-If the client chooses 2 then they want to book 2 tickets etc etc.
I'm looking for a method to implement this using html, css and/or jquery/javascript if needed.
Many thanks in advance!
you can use sheepit plugin - sheepit for form cloning
go through it. it can help you a lot.
when user chooses number of seats, make a loop for each seat and repeat questions as needed. all in same form.
using php
for ($question = 0 ; $question < $_POST['SeatNumbers'] ; $question ++) { ... }
You then have to cycle thru the total number set of questions, I'm guessing you probably will use a SeatNumber input, in the above code you'll get a $SeatNumber0, $SeatNumber1 and so on.
Check to see if $SeatNumber exists, and process if it does.
Using JS, I define a max number for the options. and when user changes seat number, I show/hide each question with css "display:none"/"display:inline"
If you want to handle html content dynamically, you'll need to use Javascript.
You can hear event from your text field or your selector used for provide the number of ticket.
Try this with jQuery :
$('your_field_selector').on('change') or this $('your_field_selector').on('keyup')
If the event is triggered, you can get the value of the field with the jQuery method called "val()" :
$('your_field_selector').val()
Next insert your new html content in function of the value.
Here, There's also many jQuery method for do that like "append()","insertBefore()","insertAfter()"... etc
I think this is the sort of thing your after.
The amount of sections within the form is generated by the number selected on the slider with each dynamically generated form element having a unique id depending on which ticket its for ie: ticket 3 has a name id of name3 ticket 14 would have a name id of name14 and so on to allow proper usage of each input through your server side post functionality.
here is a working jsfiddle http://jsfiddle.net/fd78gkf3/
Excuse the generic form field names :)
<script>function showValue(newValue)
{
document.getElementById("tAmount").value = newValue;
document.getElementById("tAmountDisplay").innerHTML = newValue;
}
</script>
<script>
$(document).on("click", '#select', function() {
var formTimes = document.getElementById("tAmount").value;
$('#forms').append('<form id="ticketForm">');
for(var i = 1; i < formTimes; i++) {
$('#forms').append(i);
$('#forms').append('<div id="formPanel">');
$('#forms').append('<label>Name</label><input id="name' + i +'" type="text"/>'+'<br/>');
$('#forms').append('<label>Age</label><input id="age' + i +'"type="text"/>'+'<br/>');
$('#forms').append('<label>Gender</label><input id="gender' + i +'" type="text"/>'+'<br/>');
$('#forms').append('</div>');
}
$('#forms').append('<input type="button" id="submit" value="Submit"/>'+'</form>')
});
</script>
<span id="tAmountDisplay">0</span> Tickets
<form action="" method="post">
<input type="range" min="1" max="20" value="1" step="1" width="100px" oninput="showValue(this.value)" />
<input type="hidden" id="tAmount" name="tAmount" value=""/>
<input type="button" id="select" value="Select" />
<div id="forms">
</div>
</form>
I need to take the contents of form fields (client, phone number) validate them (most likely using regex) and concatenate them into an alert and a modify some html so on form submit I get
<p>John smith
99999999
2 wilerby dr
morrowie city
morrowie </p>
and alert("form data")..
I tried with something like var field1 = document.forms[0].elements[0].value,
but not sure how to address the fields.
Edit:
<form id="form1" action="form_action.asp">
<fieldset>
<table cellpadding="3" border="0">
<th> Order Details </th>
<tr>
<td>Client Name:</td>
<td><input id="clientname" type="text" name="clientname" value="" maxlength="20"></td>
</tr>
...
Edit 2
var name = document.getElementById('clientname').value;
function buttontest()
{
alert(clientname);
}
using this script I keep getting a [object HTMLInputElement] alert, the script is external and the script tag is in the header.
You should use DOM selectors alike document.getElementById('elementId').value.
Please read the resembling documentation about such browser APIs: https://developer.mozilla.org/en-US/docs/Web/API/document
Try add an ID to those fields, and use getElementById(). Example.
var val = document.getElementById('id_field').value;
document.getElementById('id_tag').innerHTML = val;
var clientName = document.getElementById('clientname').value;
alert(clientName);
if you already know the sequence no of the element that you want to address then only you can use the syntax you specified i.e. as follows:
document.forms[form_index].elements[form_element_index].value
form_index->the index of the particular form where the element is.
form_element_index->the index of the element in the particular form.
So you could use:
alert(document.forms[form_index].elements[0].value);
N.B.-form_index will be 0 only if the form you refer to is the first form in your document.
Otherwise
If you don't know either the sequence no of the form or the sequence no of the element in the form you should use the id attribute to refer to it(No need of any reference to the form where the element is) which is the usual approach and I personally suggest you to use this.
So in your code use the following:
alert(document.getElementById('clientname').value)
You should use document.getElementById('ID'), you can go to www.w3schools.com for more details.
I am using jQuery and bootstrap to give drop-down search suggestions.Following is the html code.But when I type something in the search form and then clear the form.Two forms apears as in the picture.Why? I am new to jQuery. Thanks for any help.
<div class="container">
<div class="row">
<div class="span6 offset3">
<form class="form-search">
<input type="text" id="month" name="month" class="input-medium search-query">
<button type="submit" class="btn">Search</button>
<div id="suggestions">
</div>
</form>
</div>
</div>
</div>
<script>
jQuery("#month").keyup(function(){
ajax('search', ['month'], 'suggestions')});
</script>
EDIT:
I am using web2py framwork.This is the search function's code:
def search():
if not request.vars.month: return dict()
month_start = request.vars.month
selected=complete('piracyfinder',month_start) #this line get the search results
return DIV(*[DIV(k['title'],
_onclick="jQuery('#month').val('%s')" % k['title'],
_onmouseover="this.style.backgroundColor='lightblue'",
_onmouseout="this.style.backgroundColor='white'"
) for k in selected])
It appears you are using the same function (i.e., search()) to fill in the suggestions as well as to create the form (though that function doesn't process the form when submitted). According to the logic, when request.vars.month is either empty or does not exist, the function returns an empty dict. This will result in the associated view (i.e., /views/[controller name]/search.html) being executed and returned. Presumably the search.html view contains the HTML code shown above. So, when you clear the input box, the keyup handler is triggered and sends an empty month variable, which results in a new copy of the form being sent back and inserted in the "suggestions" div. You can avoid this problem by checking whether request.vars.month exists:
if not request.vars.month:
return '' if 'month' in request.vars else dict()
A better approach might simply be to use different functions for the search form and the suggestions given that they do completely different things and don't share any code.
if not request.vars.month also applies to the month var existing but being empty. Therefore, it's returning the form.
You need to do one of these:
Have your "suggestions" code be in a different page/file
Add a isAJAX variable to the request (or some other way to identify AJAX requests)
Check if the variable exists, rather than checking if it is falsy.
I'm making a website using JSP and servlets and I have to now break up a list of radio buttons to insert a textarea and a button. I have got the button and textarea to hide and show when you click on the radio button it shows the text area and button. But this only appears at the top and when there are hundreds on the page this will become awkward so i need a way for it to appear underneath. Here is what my HTML looks like when complied:
<form action="addSpotlight" method="POST">
<table>
<tr><td><input type="radio" value="29" name="publicationIDs" ></td><td>A System For Dynamic Server Allocation in Application Server Clusters, IEEE International Symposium on Parallel and Distributed Processsing with Applications, 2008</td> </tr>
<tr><td><input type="radio" value="30" name="publicationIDs" ></td><td>Analysing BitTorrent's Seeding Strategies, 7th IEEE/IFIP International Conference on Embedded and Ubiquitous Computing (EUC-09), 2009</td> </tr>
<tr><td><input type="radio" value="31" name="publicationIDs" ></td><td>The Effect of Server Reallocation Time in Dynamic Resource Allocation, UK Performance Engineering Workshop 2009, 2009</td> </tr>
<tr><td><input type="radio" value="32" name="publicationIDs" ></td><td>idk, hello, 1992</td> </tr>
<tr><td><input type="radio" value="33" name="publicationIDs" ></td><td>sad, safg, 1992</td> </tr>
<div class="abstractWriteup"><textarea name="abstract"></textarea>
<input type="submit" value="Add Spotlight"></div>
</table>
</form>
Now here is what my JSP looks like:
<form action="addSpotlight" method="POST">
<table>
<%int i = 0; while(i<ids.size()){%>
<tr><td><input type="radio" value="<%=ids.get(i)%>" name="publicationIDs" ></td><td><%=info.get(i)%></td> </tr>
<%i++; }%>
<div class="abstractWriteup"><textarea name="abstract"></textarea>
<input type="submit" value="Add Spotlight"></div>
</table>
</form>
Thanks in Advance
Dean
You can easily move DOM nodes around using Node#insertBefore. (That link is to MDC, but it's a standard method and well-supported.)
Here's an example using Prototype, but you can do it with jQuery or other libraries, or just straight DOM methods like the one linked above (it's just more hassle without a library):
// Called at some point during page init to hook up the event handler
function hookRadioButtons() {
var form;
form = $('theForm'); // Assuming you put an ID on the form
form.observe('click', radioButtonClick);
}
// Event handler for radio button clicks
function radioButtonClick(event) {
var btn, div;
// Get the (extended) DOM element for the button
btn = event.findElement('input[type=radio]');
if (btn) {
// Get the (extended) DOM element for the div
div = $('theDiv'); // Assuming you gave the div an ID
// Starting from the button, go `up` to the table cell,
// then over to the following cell, and then insert the
// div at the top of it
btn.up('td').next().insert({
top: div
});
// Show the div (if it's hidden)
div.show();
}
}
That's completely off the cuff and untested (and full of assumptions), it's just to give you an idea.
you can use after(html) or before(html) you only need to add to every radiobutton a unique value but you already did that with value="<%=ids.get(i)%>"
something like this?
$("input[value='PutIdHere']").parent().after(htmlContent);
Move the div "abstractWriteup" to after the closing table tag. It's invalid code to have it inside a table without a containing row and cell anyway, and this will ensure that it appears below the table.
EDIT
I realise I may have misunderstood - you want the div to appear below the radio button which has been clicked, don't you?
You can't put <div> inside a table. It's invalid and browsers may render it in odd ways, like, as you said, as the top.
You would have to either:
close the table, put the div and then if you need more rows after that open a second table. To ensure two tables have the same row widths, you can set table-layout: fixed on the tables and add <col> elements with explicit widths for the non-liquid columns. Or,
include the textarea/submit in a new <tr><td>.
Having said that, I don't know why you're using a table here when you aren't really doing anything with the columns. A simple <div> for each radio would be easier to handle.
Since you will also only ever have one radio ticked, you can re-use the same textarea/submit elements, and just move them to the right row onclick. With JavaScript disabled they'll just stay at the bottom.
<form id="publications" method="post" action="...">
<% for(int i= 0; i<ids.size(); i++) { %>
<div>
<input type="radio" name="publicationIDs" value="<%= ids.get(i) %>" id="pid_<%= ids.get(i) %>">
<label for="pid_<%= ids.get(i) %>">
<%= info.get(i).replaceAll("&", "&").replaceAll("<", "<").replaceAll("\"", """) %>
</label>
</div>
<% } %>
<div id="abstractsubmit">
<textarea name="abstract"></textarea>
<input type="submit" value="Add Spotlight">
</div>
</form>
Note: <label> added, for better usability (can click on name to select radio). replaceAll here is acting as a poor man's HTML encoder. You need an HTML encoder every time you output text into HTML, otherwise characters like < in the text will mess up the page, and potentially create cross-site-scripting security holes.
Unfortunately, in an appalling oversight, the original version of JSP didn't include an HTML encoder. Many, many libraries for web-related software have one you can use to avoid having to write out all these replaceAll​s. Also, if you're using JSP 2.0+, you should consider using JSTL c: tags rather than scriptlets. <c:out> gives you an output-with-HTML-encoding behaviour by default.
Example script to move the abstract element about:
<script type="text/javascript">
var radios= document.getElementById('publications').elements.publicationIDs;
function update() {
// Get div containing selected radio
//
var selected= null;
for (var i= radios.length; i-->0;)
if (radios[i].checked)
selected= radios[i].parentNode;
// Move abstract div just after it
//
var a= document.getElementById('abstractsubmit');
if (selected===null) {
a.style.display= 'none';
} else {
a.style.display= 'block';
selected.parentNode.insertBefore(a, selected.nextSibling);
}
}
// Bind to all radios, and reflect initial form selectedness state
//
for (var i= radios.length; i-->0;)
radios[i].onclick= function() { setTimeout(update, 0); };
update();
</script>
setTimeout is used here because the onclick event fires before the radio have been selected to reflect the click, so update can't yet read which radio is chosen. The right thing to do would be to use onchange instead, but unfortunately that doesn't fire at a useful time in IE, so onclick is what we're left with.
update is run at the start because when you're doing forms you can never be sure what your initial state is. Browsers often try to remember form fields when returning to a page, which may result in a radio unexpectedly being ticked at start of play.
(You could make this a little shorter with jQuery. But not massively shorter.)