JavaScript, HTML, JSP onClick statement - javascript

Is there a way to use the value from a text field as the parameter value in an onclick statement for a button. For example if you have some text field named "name" and you have another button named "button" when clicked will go to the same page "page.jsp" with a parameter "par" equal to the text field value. This is what I am currently doing:
out.print("<input type = 'button' name = 'noName' value = 'Click Me' onclick =" + '"' + "window.location.href = 'http://page.jsp?par=" + document.form.name.value + "'" + '"');
But for some reason it doesn't like the par=" + document.form.name.value
Any suggestions?

Like this?
<script>
function doSomething(txt){
alert(txt); //alert the text maybe?
//do more things...
}
</script>
<input onClick="doSomething(this.value)">
this.value means the value in the textfield.

String s = "<input type='button' name='noName' value='Click Me' onclick="
+ "\"window.location.href='http://page.jsp?par="
+ document.form.name.value + "'\"";
Well, that's pretty confusing.
document etc. has zero meaning on the server side. Why aren't you doing this in JavaScript, where it would be a lot easier? Why isn't this in the JSP, where it would be trivial?
If you want to access a form value from a servlet, (a) that form value must have been submitted, and (b) you access it via request.getParameter("parameterName"). But I find it impossible to believe that's the easiest way to do it.

Related

Returning the label value of a radio button using javascript/jQuery

I've recently started learning jQuery and for the first time after weeks, I didn't manage to find an answer to my problem on this site which leads me to think I've screwed when creating my radio buttons.
A little breakdown of what I do: I have this simple web page which contains a div:
<div id="skins">
</div>
In this div, I will push radio buttons that are generated by going through a for loop and assigning to each one of them a text which is stored in an array named skins
for(var i in skins) {
$("#skins").append("<input type='radio' class='result_skin' name='skin'>" + skins[i].name + "</br>")
}
I add a break at end of each radio button so they will sit one on top of each other and not be generated one after another (so it looks like a list)
Then I want to check which radio button has been checked and return its label text which after research, it can be done this way:
$("#skins").click(function() {
$("input:radio:checked").each(function() {
var text = $(this).text()
console.log(text)
})
})
This is where the problem is. The variable text in this case is returned as an empty string which leads me to thing that the way I created a radio button is incorrect.
Could someone help me with this small issue?
Radio buttons do not have text. Only elements that can encapsulate content between their opening and closing tags can have text and radio buttons don't get a closing tag, so they can never "contain" anything, let alone text. Instead, they have a value and that's where their data and ultimate meaning resides, not from the text caption (what you are calling label) that is next to them says.
So, really you need to give each of your radio buttons a value and then you can get that value with:
$(this).val()
not:
$(this).text()
Try this:
var skinValues = ["one","two","three","four","five", "Champion zed"];
// Don't use for/in loops with arrays, use .forEach()
skinValues.forEach(function(skin){
// each radio buttons needs a unique value and that's where its data is stored
$("#skins").append("<input type='radio' class='result_skin' name='skin' value='" + skin + "'>" + skin + "</br>")
});
$("#skins").click(function(){
$("input:radio:checked").each(function(){
var text = $(this).val() // Radio buttons don't have text, they have a value
console.log(text)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="skins"></div>
The basic use of radio buttons is the fact that you can force people to pick one out of many choices. To achieve this effect you will have to use the same name attribute on the radio buttons you want to group together.
To find out what radio button someone has selected, you can then indeed check with jQuery using the following code:
$('input[name=radioName]:checked', '#myForm')
with '#myForm' being optional, if you want to search in a certain form.
The text you write next to an input is totally unassociated with it. To get the value of the input you should add a value attribute, or another data attribute. More information about data attributes can be found here.
Piecing all this information together, your code should look something like this:
Creating the skin list
for(var i in skins){
$("#skins").append("<input type='radio' class='result_skin' name='skin' value='" + skins[i].name + "'>" + skins[i].name + "</br>")
}
Accessing "the text" next to the input
var text = $('input[name=skin]:checked').val();
Since you use values for the radio buttons, try not using .text() but .val() instead
The text associated to the radio isn't linked to the input tag. So you have to wrap the text and the input into a parent tag (something like a div):
<div>
<input type="checkbox"/>
<span class="label">Text</span>
</div>
When you want to check the text
$("input:radio:checked").each(function(){
var text = $(this).parent().find( "span" ).text()
console.log(text)
})
Updated with JiFus updated idea
You can use data-attribute or value attribute
for(var i in skins){
$("#skins").append("<input type='radio' class='result_skin' name='skin' data-skin-name='" + skins[i].name + "'>" + skins[i].name + "</br>")
}
And call it with dataset
$("input:radio:checked").each(function(){
var text = $(this).dataset['skin-name']
console.log(text)
})

Get function output to different HTML page by JavaScript

I have a function that gets all selected values from selects on my page as a text. I need a button that onclick opens new "blank" with different HTML page and puts output from my selectgetting function to text box on new page.
How to make that by JavaScript?
var w = window.open('form.html', 'blank', 'scrollbars=yes,toolbar=no,width=500,height=950')
var box = w.getElementById('input_16');
box.value = "bodystyle: " + body + "<br>" + "color: " + color;
w.focus();
this should work for changing the box text shouldn´t it? I first open second HTML in new window then i get its textbox by id and change its value. Why doesn´t it work?
Thank you
to pass your dropdown value to the _blank page you could add it as parameter in URL.
Them read it with Javascript from url on next page and put it in your text box.
So:
1. Read the value
2. Add to URL
3. Read the value from url
4. Add value to textbox
Good luck.
EDIT: this does 1 and 2.
<div>
<input type="button" value="click me" />
<input type="text" id="input_16" value="input16" />
</div>
<script>
$(function(){ $("input[type='button']").on('click',function(){ var val = document.getElementById('input_16').value; window.open('form.html&param1='+val, '_blank', 'location=yes,height=570,width=520,scrollbars=yes,status=yes') })})
</script>
http://jsfiddle.net/2BejP/

Save Users Input in a Variable, and Post that Variable

I have a small form and When I click the Join button, and enter my information, I want it to save the value of the Username form, and then replace the Join and Signup button with their name or "Hello" + name.
So I have a JSFiddle Here: http://jsfiddle.net/LCBradley3k/t3HF5/
I would think it would be something like the following code, but that doesn't work:
var name = document.getElementById("name");
Then I would want it to put name in some type of div that replaces the two button at the top.
If you're using jQuery (which your jsfiddle indicates you are), this should be fairly trivial.
var name = $('#name').val();
Hope that helps!
Using pure javascript (no jQuery), if it's an input element, to get the input value use:
var name=document.getElementById("name").value;
To replace a div's content with name:
document.getElementById("div_id").innerHTML=name;
You can also use html:
document.getElementById("div_id").innerHTML="<p>" + name + "</p>";
Or replace the div's value:
document.getElementById("div_id").value=name;

How do I submit a javascript variable using a round trip to the server

I have a string that I am building via javascript. For the purposes of this example:
var cereal = 'my super cereal string';
I have a button on the page:
<button id="save" type="submit" name="submit">Save</button>
How do I submit this string using a round trip (I do not want to use ajax). I am using jquery in this application.
What is the best way to accomplish this?
not sure if it's the best or most elegant way, but you could have a form with a hidden field. set the string to the hidden field, and then submit the form.
You could assign a click listener to the button that builds up a throwaway form with an input containing your string:
var cereal = 'my super cereal string';
$("button#save").click(function() {
var form = "<form id='hidden-form' style='display:none' method='POST' action='/echo/json'><input name='cereal' value='" + cereal + "' /></form>";
$("body").append(form);
$("form#hidden-form").submit();
});
Replacing the form's action with whatever you want to POST to.
Check it out: http://jsfiddle.net/andrewwhitaker/MNtwY/
Here's an option using a GET request:
var cereal = 'captain crunch';
$('#save').click(function () {
window.location.href = "http://www.google.com/search?q=" + cereal;
});

jQuery validation plugin - removing elements

I'm using the jQuery validation plugin. On most of my input type... tags I have class='required'.
When I submit the page, via JavaScript, the controls on the page that have this class are found. However, there are a handful of checkboxes that I don't need to validate.
I've tried removing the class code completely from the input tag, also tried class='cancel', and class='required:false.
When doing any of those things though when the form submits it can't find the checkbox control.
How do I still keep the ability to do Request.Form and find my checkbox object but at the same time when the form submits don't apply validation to this particular control.
Thank you.
Edit here.
This is what I'm using without the "checked" code and ternary operator. In my input tag I'm calling a function like this...
sb.Append(" <td><input type='checkbox' id='chkFlashedCarton' name='chkFlashedCarton' " + strDisabled + " value='true' " + GetPackagingSizeTypeControlValue("chkFlashedCarton") + " />" + crlf);
Inside that function is where I check for the True or False coming back, like this.
case "chkFlashedCarton":
strResultValue = pst.FlashedCarton.ToString();
if (strResultValue == "True")
{
strResultValue = " checked";
}
break;
strResultValue is what is returned back.
Does this help to see? Thank you.
I don't think the checkbox not appearing is related to the validation issue. By default, inputs without values are not posted back with the form. One way around that for checkboxes is to have an hidden form field per checkbox that sets the opposite value with the same name as the checkbox. When the form is posted back with the checkbox checked, you'll get both values. If the checkbox isn't checked, you'll get the default value (from the hidden field). Thus, you only need to check if the value for the checkbox contains the non-default value and act appropriately on the server side.
<input type='checkbox' name='cb1' value='true' /> Check Me
<input type='hidden' name='cb1' value='false' />
You can then omit the required class and be assured that you will always get some value for the checkbox.
On the server side, then you do something like:
bool cb1Flag = false;
if (Request.Form["cb1"].ToUpper().Contains("TRUE"))
{
cb1Flag = true;
}
Edit (based on your edit)
Try this:
sb.Append(" <td><input type='checkbox' id='chkFlashedCarton' name='chkFlashedCarton' " + strDisabled + " value='true' " );
if (pst.FlashedCarton)
{
sb.Append( " checked='checked'" );
}
sb.Append( " />" + crlf);

Categories