How to i pass variable value to input text value? - function

I would like to compare user input with predefined value on same jsp page. If the input value is same as expected, then i allow user go ahead to submit the request form. But i don't know how set the predefined value for checking. Thanks.
<tr><td>Application</td></tr>
<%
String strDBCode = "123456789";
out.println("<tr><td><b>Please input your pass code here:</b></td></tr>");
out.println("<tr><td><input type='text' name='strPassCode' value=''></td></tr>");
out.println("<tr><td><input type='hidden' name=strDBPassCode size='15' maxlength='15' value=strDBCode id='b'></td></tr>");
out.println("<tr><td><input type='button' name='chkPassCode' value=' Check ' onClick='return chkPCode()'></td></tr>");
%>
<script type="text/javascript">
function chkPCode()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if (a.value != b.value) {
alert("Not Match!");
valid = false;
}
else {
alert("Match");
valid = true;
}
return valid;
}
</script>
I expect b value should be "123456789", but b always equal to "strDBPassCode". I have try set
out.println(" id='b'>");
It return error. Since the input already inside <% %>.
Apart from that, how to disable the input text box if valid return is true?
Any idea? thanks.

This is because you are not referring to the variable you declared.
out.println("<tr><td><input type='hidden' name=strDBPassCode size='15' maxlength='15' value="+strDBCode+" id='b'></td></tr>");
__________↑
Similar way, you can update the name attribute in above code.
Do not write scriptlets in JSP, because scriptlets shouldn't be used in JSPs for more than a decade. Learn the JSP EL, the JSTL, and use servlet for the Java code.
See How to avoid Java Code in JSP-Files?

<script type="text/javascript">
function chkPCode()
{
var a = document.getElementById("a");
var b = document.getElementById("b");
var valid = true;
if (a.indexOf(b) == -1) {
alert("Not similar!");
valid = false;
}
else {
alert("Input value exist!");
valid = true;
}
return valid;
}
</script>

Related

email check and comma separated check jQuery codes work correctly in separation but not when mixed for disabling the submit button

I have to functions that each of them looks for an email being valid and the other one looks for an input being comma separated (not sure if I have the best comma separated jQuery code).
However, when I write a proper comma separated input in the input box, it still allows me to click on the submit button which is strange because the email is empty and I expect the submit button to stay disabled. Each of these two functions work correctly separately.
$("#category_names").on('keyup', function (event) {
$(".error").hide();
let hasError = false;
let isValid = true;
$('#category_names').each(function() {
if (($.trim($(this).val()).indexOf(",") == -1)) {
//alert('Please separate multiple keywords with a comma.');
$('#commaerror').show();
hasError = true;
} else {
$('#commaerror').hide()
hasError = false;
}
});
$('button[type="submit"]').prop('disabled', hasError);
})
$("#email").on('keyup', function() {
$(".error").hide();
let hasError = false;
let emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
let emailAddressVal = $(this).val();
if (emailAddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if (!emailReg.test(emailAddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
$('button[type="submit"]').prop('disabled', hasError);
})
You need to check both (all, if there are other inputs as well) conditions are valid in each event handler. It's probably simplest to put all the validation code into a function and call that in the event handler. For example:
function validate() {
$(".error, #commaerror").hide();
let hasError = false;
// validate category names
$('#category_names').each(function() {
if ($(this).val().indexOf(",") == -1) {
//alert('Please separate multiple keywords with a comma.');
$('#commaerror').show();
hasError = true;
}
});
// validate email
let emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
let emailAddressVal = $('#email').val();
if (emailAddressVal == '') {
$("#email").after('<span class="error">Please enter your email address.</span>');
hasError = true;
}
else if (!emailReg.test(emailAddressVal)) {
$("#email").after('<span class="error">Enter a valid email address.</span>');
hasError = true;
}
return hasError;
}
$("#category_names, #email").on('keyup', function(event) {
$('button[type="submit"]').prop('disabled', validate());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-3">
<label data-error="wrong" data-success="right">Enter your email</label>
<input type="email" class="form-control validate purple-border" id="email">
<br/>
<label>Enter categories:</label>
<input type="text" id="category_names" />
<br/>
</div>
<button type="submit" class="btn btn-purple purple-border" disabled="disabled">Perform Frame Classification</button>
Note I've cleaned up your category_names code a bit, but you need to add further checking so that if there is only one value it still passes, or that something like abc, doesn't pass. You might find something like
$(this).val().match(/^\s*\w+(\s*,\s*\w+)*\s*$/)
more useful.

Make basic search in array with if and else

I am trying to make a basic search function. if input.value does exist in array alert message, if not, push it to array ans show in HTML. I think I have already most of work done, but there is somewhere a mistake. Thank you in advance for your help guys .)
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value = myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
In javascript, there are 2 ways to do a comparison.
Strict Equality Operator === strict equality operator.
If you are not sure about the exact datatype for the values being compared, then you can use the == for comparison.
The line document.getElementById("inputForMyDict").value = myDict[i] needs comparison operator and not the assignment operator (=). So you need to replace the = with either == or ===.
so your javascript code should look like
var buttonSave = function() {
for (var i = 0; i < myDict.length; i++) {
if (document.getElementById("inputForMyDict").value == myDict[i]) {
// If you know exact data type, then use the below line instead and comment the above line if (document.getElementById("inputForMyDict").value === myDict[i]) {
alert("your input is already in your list");
} else {
myDict.push(document.getElementById("inputForMyDict").value);
document.getElementById("demo").innerHTML = myDict;
}
}
}
Update1: Based on the clarification, provided by comments, you don't need to have a for loop to check for existence of element in array. Javascript provides a convenient way by indexOf method on an array. indexOf method check for the existence of an element in an array and returns the index of the element in the Array. However, if the element is not found then it returns -1.
Full code below which should work.
<!DOCTYPE html>
<html>
<body>
<div id="main">
<input id="inputForMyDict">
<button id="ButtonForInputSave" onclick="buttonSave()">Speichern</button>
<p id="demo"></p>
</div>
<script>
var myDict = [];
var buttonSave = function() {
//for (var i = 0; i < myDict.length; i++) {
var valueInTextbox = document.getElementById("inputForMyDict").value;
if(myDict.indexOf(valueInTextbox) > -1){
alert("your input is already in your list");
} else {
myDict.push(valueInTextbox);
document.getElementById("demo").innerHTML = myDict;
}
}
//}
</script>
</body>
</html>

Problem in getting right result for select box

I am using jQuery as:
$(document).ready(function(){
test("price");
alert("hi");
$("#item2").change(function()
{
sort= $("#item2").val();
test(sort);
});
});
Function test() is some JavaScript function, my problem is when page loads function calls by "price" parameter. Now when I select some item from select box function test() is called using sort parameter (verify by alert box). but I am not getting the correct result. I mean when I select option from select box than also my result of test() is as with "price" , I suppose it might be the problem because of jQuery's $(document).ready(function(){,. test() function make some html code based on the parameter and show it on the web page.
Please suggest me what can be the solution
EDIT:
function test() is :
function test(sort)
{
<%
Ampliflex ms = Ampliflex.getInstance();
String solrIP = ms.getSolrIP();
String solrPort = ms.getSolrPort();
String rows = ms.getSearchResultCount();
%>
solrIP='<%= solrIP %>'; // get Solr IP address
solrPort='<%= solrPort %>'; // get Solr Port number
rows='<%= rows %>'; // get number of results to return
solrURL="http://"+solrIP+":"+solrPort;
var query="${searchStr}"; // get the query string entered by ECommerce user
query=query.replace(/[^a-zA-Z 0-9*?:.+-^""_]+/g,''); // Remove special characters
query=query.replace(/\*+/g,'*'); // Replace multiple occurrence of "*" with single "*"
var newquery=query;
if(parseInt(query)==NaN)
{
var lowerCaseQuery=query.toLowerCase();
newquery=lowerCaseQuery;
}
else{
var lowerCaseQuery=query;
}
// sort= document.getElementById("item2").value;
$.getJSON(solrURL+"/solr/db/select/?qt=dismax&wt=json&&start=0&rows="+rows+"&q="+lowerCaseQuery+"&hl=true&hl.fl=text&hl.usePhraseHighlighter=true&sort="+sort+" desc&json.wrf=?", function(result){
var highlight = new Array(result.response.numFound);
$.each(result.highlighting, function(i, hitem){
var rg = /<em>(.*?)<\/em>/g;
var res = new Array();
var match = rg.exec(hitem.text[0]);
while(match != null){
res.push(match[1])
match = rg.exec(hitem.text[0]);
}
highlight[i]=res[0]
for (j=1 ;j<res.length;j++)
{
highlight[i]= highlight[i]+","+res[j];
}
});
var html="<table><tr>"
var count=0;
var alt="NoImage";
var size="3pt";
var id;
var flag=1; // Flag for error messages
border="1";
// If no search results
if(result.response.numFound==0)
{
var msg= "<hr /><font size="+size+" >We're sorry, we found no results for <b>"+document.getElementById("queryString").value+"</font><hr />";
}
else
{
/* var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+document.getElementById("queryString").value+"</b> keyword</font><hr /> ";*/
if (newquery==lowerCaseQuery)
{
var msg= "<hr /><font size="+size+" >Total Results Found <b> "+ result.response.numFound+"</b> for "+"<b>"+query+"</b> </font><hr /> ";
}
else
{
var msg= "<hr /><font size="+size+" >There were no exact matches for <b> "+ query+"</b> , so we searched automatically for "+"<b>"+query+"</b> and yielded "+result.response.numFound+" result(s)</font><hr /> ";
}
// Parse solr response and display it on web page
$.each(result.response.docs, function(i,item){
var word = new Array();
word=highlight[item["UID_PK"]].split(",");
var result="";
var j=0;
for (j=0 ;j<=item.text.length;j++)
{
result = result+item.text[j]+"<br>";
}
for (j=0 ;j<word.length;j++)
{
result=result.replace(word[j],'<em>' + word[j] + '</em>');
}
html+="<td><table>";
var src=item.image;
id="id";
if(src!= null && src!= ""){
html+="<p><tr><td><br>"+"<img id= "+id+ " src="+src+ " border="+border+ " /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+ item.image+"</td></tr>";
}
// If not insert a default image
else
{
src="images/products/default.jpg";
html+="<tr><td><br><p>"+"<img id= "+id+ " src="+src+ " border="+border+" /></td></tr>";
count=count+1;
html += "<tr><td><b>ImagePath</b> "+"No image path found" +"</td></tr>";
}
html += "<tr><td>UID_PK: "+ item.UID_PK+"</td></tr>";
html += "<tr><td>Name: "+ item.name+"</td></tr>";
html+="<tr><td><b>Price: $"+item.price+"</td></tr>";
html+="<tr><td> "+result+"<br></td></tr>";
html+="</p></table></td>"
if(count%3==0)
{
html+="</tr>"
html+="<tr>"
}
});
html+="</table>"
}
$("#text_container").html(msg);
$("#result").append(html);
}
});
});
}
Your question isn't particularly clear, but your alert code only fires when the document is ready - it is not inside the "change" event function.
Try using the following to see what value is being returned when you change the select box:
$(document).ready(function(){
test("price");
$("#item2").change(function()
{
sort= $("#item2").val();
alert(sort);
test(sort);
});
});
When changing the select box, you should get an alert with the value you have chosen, which will help you understand why the test() function isn't functioning as you expect.
If you amend your question to include the HTML of the select box and the test() function itself I will amend my answer to help.
The JQuery code that you have posted is working fine. Demo: http://jsfiddle.net/DtnUr/
We need more details to figure out the issue, such as your HTML code and JS functions.

How can I pre-populate html form input fields from url parameters?

I have a vanilla html page which has a form in it. A requirement has come in to be able to pre-populate the form via the url. Something like:
http://some.site.com/somePage.html?forename=Bob&surname=Jones
I can't seem to find any simple solution to this. Can someone point me in the right direction with some javascript to accomplish this? Happy to use a javascript solution, but I'd prefer to avoid pulling in an entire library just for this single use (none are currently used). Thanks.
Use a custom query string Javascript function.
function querySt(ji) {
hu = window.location.search.substring(1);
gy = hu.split("&");
for (i=0;i<gy.length;i++) {
ft = gy[i].split("=");
if (ft[0] == ji) {
return ft[1];
}
}
}
var koko = querySt("koko");
Then assign the retrieved value to the input control; something like:
document.getElementById('mytxt').value = koko;
Are you using PHP? If so, that makes things much easier. Assuming your link as above, you can use:
<?php
$forename = $_GET['forename'];
$surname = $_GET['surname'];
?>
----------
<input id='forename' type='text' value='<?php echo $forename; ?>' >
<input id='surname' type='text' value='<?php echo $surname; ?>' >
That should pre-populate for you.
function getUrlVars()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var get = getUrlVars();
//returns get['forename'] == bob; surname == jones
Here is the builtin way, for reference:
https://developer.mozilla.org/en-US/docs/Web/API/URL/searchParams
You can instantiate the current address's parameters as a URL object without importing any libraries as shown here:
let params = (new URL(document.location)).searchParams;
Then you can reference them directly:
let name = params.get('name');
Or you can cycle through them with a loop such as:
for (const [key, value] of params.entries()) {}

Insert a Link Using CSS

I'm hand-maintaining an HTML document, and I'm looking for a way to automatically insert a link around text in a table. Let me illustrate:
<table><tr><td class="case">123456</td></tr></table>
I would like to automatically make every text in a TD with class "case" a link to that case in our bug tracking system (which, incidentally, is FogBugz).
So I'd like that "123456" to be changed to a link of this form:
123456
Is that possible? I've played with the :before and :after pseudo-elements, but there doesn't seem to be a way to repeat the case number.
Not in a manner that will work across browsers. You could, however, do that with some relatively trivial Javascript..
function makeCasesClickable(){
var cells = document.getElementsByTagName('td')
for (var i = 0, cell; cell = cells[i]; i++){
if (cell.className != 'case') continue
var caseId = cell.innerHTML
cell.innerHTML = ''
var link = document.createElement('a')
link.href = 'http://bugs.example.com/fogbugz/default.php?' + caseId
link.appendChild(document.createTextNode(caseId))
cell.appendChild(link)
}
}
You can apply it with something like onload = makeCasesClickable, or simply include it right at the end of the page.
here is a jQuery solution specific to your HTML posted:
$('.case').each(function() {
var link = $(this).html();
$(this).contents().wrap('');
});
in essence, over each .case element, will grab the contents of the element, and throw them into a link wrapped around it.
Not possible with CSS, plus that's not what CSS is for any way. Client-side Javascript or Server-side (insert language of choice) is the way to go.
I don't think it's possible with CSS. CSS is only supposed to affect the looks and layout of your content.
This seems like a job for a PHP script (or some other language). You didn't give enough information for me to know the best way to do it, but maybe something like this:
function case_link($id) {
return '' . $id . '';
}
Then later in your document:
<table><tr><td class="case"><?php echo case_link('123456'); ?></td></tr></table>
And if you want an .html file, just run the script from the command line and redirect the output to an .html file.
You could have something like this (using Javascript). Inside <head>, have
<script type="text/javascript" language="javascript">
function getElementsByClass (className) {
var all = document.all ? document.all :
document.getElementsByTagName('*');
var elements = new Array();
for (var i = 0; i < all.length; i++)
if (all[i].className == className)
elements[elements.length] = all[i];
return elements;
}
function makeLinks(className, url) {
nodes = getElementsByClass(className);
for(var i = 0; i < nodes.length; i++) {
node = nodes[i];
text = node.innerHTML
node.innerHTML = '' + text + '';
}
}
</script>
And then at the end of <body>
<script type="text/javascript" language="javascript">
makeLinks("case", "http://bugs.example.com/fogbugz/default.php?");
</script>
I've tested it, and it works fine.
I know this is an old question, but I stumbled upon this post looking for a solution for creating hyperlinks using CSS and ended up making my own, could be of interest for someone stumbling across this question like I did:
Here's a php function called 'linker();'that enables a fake CSS attribute
connect: 'url.com';
for an #id defined item.
just let the php call this on every item of HTML you deem link worthy.
the inputs are the .css file as a string, using:
$style_cont = file_get_contents($style_path);
and the #id of the corresponding item. Heres the whole thing:
function linker($style_cont, $id_html){
if (strpos($style_cont,'connect:') !== false) {
$url;
$id_final;
$id_outer = '#'.$id_html;
$id_loc = strpos($style_cont,$id_outer);
$connect_loc = strpos($style_cont,'connect:', $id_loc);
$next_single_quote = stripos($style_cont,"'", $connect_loc);
$next_double_quote = stripos($style_cont,'"', $connect_loc);
if($connect_loc < $next_single_quote)
{
$link_start = $next_single_quote +1;
$last_single_quote = stripos($style_cont, "'", $link_start);
$link_end = $last_single_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size);
}
else
{
$link_start = $next_double_quote +1;
$last_double_quote = stripos($style_cont, '"', $link_start);
$link_end = $last_double_quote;
$link_size = $link_end - $link_start;
$url = substr($style_cont, $link_start, $link_size); //link!
}
$connect_loc_rev = (strlen($style_cont) - $connect_loc) * -1;
$id_start = strrpos($style_cont, '#', $connect_loc_rev);
$id_end = strpos($style_cont,'{', $id_start);
$id_size = $id_end - $id_start;
$id_raw = substr($style_cont, $id_start, $id_size);
$id_clean = rtrim($id_raw); //id!
if (strpos($url,'http://') !== false)
{
$url_clean = $url;
}
else
{
$url_clean = 'http://'.$url;
};
if($id_clean[0] == '#')
{
$id_final = $id_clean;
if($id_outer == $id_final)
{
echo '<a href="';
echo $url_clean;
echo '" target="_blank">';
};
};
};
};
this could probably be improved/shortened using commands like .wrap() or getelementbyID()
because it only generates the <a href='blah'> portion, but seeing as </a> disappears anyway without a opening clause it still works if you just add them everywhere :D