Basic JavaScript events - javascript

I'm new to JavaScript. Here's my code:
<script>
function text_input_type(type)
{
if(type=='list'){
document.getElementById("note_input").innerHTML="<input type=\"text\" name=\"body\">";
}
else{
document.getElementById("note_input").innerHTML="<textarea id=\"note_input\" name=\"body\" cols=\"27\" rows=\"5\"></textarea>";
}
}
</script>
<textarea id="note_input" name="body" cols="27" rows="5"></textarea>
<input type="radio" name="type" value="text" onclick=text_input_type('list') />
<input type="radio" name="type" value="list" onclick=text_input_type('text') />
I want it so that depending on which radio button you press it changes from a textarea to a input text type. The problem is instead of changing the input from a textbox to a smaller text input it just prints the code inside the box.

Hope this helps you in solving your problem.
<script>
function text_input_type(type)
{
if(type=='list'){
document.getElementById("note_input").innerHTML="<input type=\"text\" id=\"note_input1\" name=\"body\">";
}
else{
document.getElementById("note_input").innerHTML="<textarea id=\"note_input1\" name=\"body\" cols=\"27\" rows=\"5\"></textarea>";
}
}
</script>
<div id="note_input"><textarea id="note_input1" name="body" cols="27" rows="5"></textarea></div>
<input type="radio" name="type" value="text" onclick=text_input_type('list') />
<input type="radio" name="type" value="list" onclick=text_input_type('text') />
Try this code, you will get what you want.

Your code is correct, except for a small change.
<html>
<body>
<input type="radio" name="type" value="text" onclick="text_input_type('list');" />
<input type="radio" name="type" value="list" onclick="text_input_type('text');" />
<div id="note_input">
</body>
</html>
Should work fine

Bind the click handlers with Javascript too—inline Javascript isn't really necessary:
var elems = [].slice.call( document.getElementsByTagName("input") );
elems.forEach( function( elem ){
elem.onclick = function(){
var type = this.value;
if( type === 'list' ){
alert("type is list");
} else {
alert("type is not list");
}
};
});
Example.
I'm aware that this can be a little complicated. What we're simply doing is attaching a click function to each of the input tags on the page. We set the value of the clicked input tot he type variable and check if that variable is equal to the string list. If it is, then we fire the code in the if. If not, we fire the code in the else.
Essentially what this does is make it easier for you. You just put this code in your JS file and you don't have to worry about assigning the onclick on the elements themselves (and it looks you were doing it for two of them).
However, your code will work if you surround the onclick with quotes, like so:
onclick="text_input_type('list');"

Related

How I can get the value of the input type radio using jQuery the value contains spaces

I used this code I also used AJAX in my page
$html.='<div><p id="question" name="qid">Q.'.$result['question_no'].': '.$result['question'].'</p></div>
<label style="padding-top:15px;">
A <span style="padding-left: 15px;"><input type="radio"';
if (isset($result['answer']) && $result['answer']==$result['choice1']) {
$html.= 'checked="checked"';
}
$html.=' name="answer" id="option" value='.$result['choice1'].'>'.$result['choice1'].'</span>
</label>
</div>
And the jQuery part is
var answer = $("form input[type='radio']:checked").val();
alert(answer);
The value contain spaces like 'primary key' but I got only primary how can I get value with spaces
The solution is really simple you just forgot to put double quotes for the value attribute, value attribute must be wrapped in double quotes here is the corrected code,
$html.='<div><p id="question" name="qid">Q.'.$result['question_no'].': '.$result['question'].'</p></div>
<label style="padding-top:15px;">
A <span style="padding-left: 15px;"><input type="radio"';
if (isset($result['answer']) && $result['answer']==$result['choice1']) {
$html.= 'checked="checked"';
}
$html.=' name="answer" id="option" value="'.$result['choice1'].'">'.$result['choice1'].'</span>
</label>
</div>';
Now the jquery will pick the value correctly
Why don't you ensure that the value comes in snake_case like primary_key, then process it to what you want after getting it with JQuery.
Something like:
var answer = $("form input[type='radio']:checked").val();
alert(answer.split("_"));
hi here is a working solution for your problem. feel free to modify the code to make it fit for your needs
<!-- including jquery library -->
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
/* When input of type button is clicked then call this function */
$("input[type='button']").click(function(){
/* load value of input with name gender in a JS variable radioValue */
var radioValue = $("input[name='gender']:checked").val();
/* check if there is some value in radioValue variable... if there is no value then if block will not execute */
if(radioValue){
alert(radioValue);
}
});
});
</script>
<input type="radio" name="gender" value="Gender male">Male
<input type="radio" name="gender" value="Gender female">Female
<input type="button" value="Get Value"></p>

Checkboxes, javascript runs 2 times through function if I click on text

I want to click on a checkbox and if I click this box it should run a function what gets an ID and saves it into an array or deletes it from the array if it still exists in the array.
That works, but if I click on the text beside the box the function runs twice. It first writes the ID into the array and then deletes it.
I hope you can help me so that I can click on the text and it just runs once
HTML
<label><input type="checkbox" value="XXX" >Active</label>
JavaScript/jQuery
function addOrRemoveBoxes(ID){
if(boxArr.indexOf(ID) != -1){
removeFromArray(ID)
}
else{
boxArr.push(ID);
}
}
$(".checkBoxes").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
The problem is probably that your label and your input are picking the click. Try to bind it only to input. Like this:
$(".checkBoxes input").unbind().click(function() {
event.stopPropagation();
addOrRemoveBoxes($(this).find('input').val());
});
Your HTML is structured bad. When your label is clicked it triggers a click event for the input so you have to separate the input form the label like: <input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label>. Also your jQuery makes no sense, why do you use unbind()? And we can't see what removeFromArray() does (we can guess but I prefer to see all code used or note that you use pseudo code).
I made this in 5 min: (hopes it helps you)
$(document).ready(function(){
window.boxArr = [];
$(document).on('click','[name=opt1]',function(){
addOrRemoveBoxes(this.value);
//show contents of boxArr
if(boxArr.length == 0){
$('#output').html('nothing :/');
}
else{
$('#output').html(boxArr.join(" -> "));
}
});
});
function addOrRemoveBoxes(ID){
var arrayIndex = boxArr.indexOf(ID);
if(arrayIndex > -1){
boxArr.splice(arrayIndex, 1);
}
else{
boxArr.push(ID);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Choose</h1>
<input type="checkbox" name="opt1" id="opt1_1" value="ENG"> <label for="opt1_1">hello</label> <br>
<input type="checkbox" name="opt1" id="opt1_2" value="DUT"> <label for="opt1_2">hallo</label> <br>
<input type="checkbox" name="opt1" id="opt1_3" value="SWE"> <label for="opt1_3">hej</label>
<br><br><h2>Array contains:</h2>
<div id="output">nothing :/</div>
Side note: with [name=opt1] we select all the elements with name="opt1" attribute.

Can I pass a variable textarea id to a JavaScript function?

I've run into a follow-up problem with this excellent solution:
Select checkbox when clicking in textarea (JavaScript?).
I need to apply the solution to more than one textbox in the same form. Is it possible in any way to alter the code into something like this (not working):
<html>
<body>
<textarea id="iamtextarea" rows="4" cols="10" onfocus="onFocusTextArea('iamtextarea');" onblur="onBlurTextArea('iamtextarea');">Enter some text in textbox</textarea>
<input type="checkbox" name="iamcheckbox" id="iamcheckbox" checked="checked"> I am checkbox<br>
<input type="hidden" name="hiddenString" id="hiddenString" value="Enter some text in textbox">
</body>
</html>
<script type="text/javascript">
function onFocusTextArea(variableName) {
document.getElementById("iamcheckbox").checked = false;
}
function onBlurTextArea(variableName) {
if(document.getElementById(variableName).value==document.getElementById("hiddenString").value) {
document.getElementById("iamcheckbox").checked = true;
}
}
</script>
What I want to do is to pass a variable id of the textarea to the javascript function so that I can use the same function for more than one textarea. Is that possible?
See jsfiddle here. This takes an element and a checkboxid
function onFocusTextArea(checkboxId) {
document.getElementById(checkboxId).checked = false;
}
function onBlurTextArea(element, checkboxId) {
if (element.value === "") {
document.getElementById(checkboxId).checked = true;
}
}
Some sample HTML
<textarea id="iamtextareaone" onfocus="onFocusTextArea('checkboxone');" onblur="onBlurTextArea(this, 'checkboxone');"></textarea>
<textarea id="iamtextareatwo" onfocus="onFocusTextArea('checkboxtwo');" onblur="onBlurTextArea(this, 'checkboxtwo');"></textarea>
<input type="checkbox" id="checkboxone" checked="checked">Checkbox One<br>
<input type="checkbox" id="checkboxtwo" checked="checked">Checkbox Two<br>

How to manipulate Get query?

I have the following form from http://regain.sourceforge.net/:
<form name="search" action="search.jsp" method="get">
<p class="searchinput">
<b>Suchen nach: </b>
<input name="query" size="30"/>
<select name="order" size="1" ><option selected value="relevance_desc">Relevanz</option><option value="last-modified_asc">Dokumentendatum aufsteigend</option><option value="last-modified_desc">Dokumentendatum absteigend</option</select>
<input type="submit" value="Suchen"/>
</p>
</form>
the search form works fine. The URL looks like the following:
http://localhost:8080/regain/search.jsp?query=queryfieldvalue&order=relevance_desc
Now I want to add a checkbox to manipulate the value of the input field query.
If the checkbox is checked then the query value should look like filename:"queryfieldvalue"
http://localhost:8080/regain/search.jsp?query=filename%3A%22queryfieldvalue%22&order=relevance_desc
What's the best way to do this? Javascript? Do you have a short example for me because I'm really new to javascript.
Thanks a lot in advance.
one way with pure javascript (without jquery) would be
<script type="text/javascript">
function handler()
{
var check = document.getElementById('check');
var query = document.getElementsByName('query')[0];
if(check.checked)
{
query.value = "filename:\"" + query.value + "\"";
}
else
{
query.value = query.value.replace(/^filename:"/, "").replace(/"$/, "");
}
}
</script>
<form>
<input type="text" name="query" />
<input type="checkbox" id="check" onclick="handler()" />box
</form>
it should more or less work, it would be safer if you give query input field an id and then reference it by id, not name
if you use jQuery, something like this should do:
<input type="checkbox" id="chkQuery">Pass queryfield</input>
<script>
$(document).ready(function{}
$("#chkQuery").click(function(){
if ($(this).is(':checked'))
$("input[name='query']").val("filename:queryfieldvalue");
else
$("input[name='query']").val("queryfieldvalue");
});
});
</script>

Javascript Logic Problem

I know only what I need but I do not know how to get that done.
This is the logic of the code, I really hope some of you has the solution.
How can I create in javascript or jQuery a function that will do the following?
If that checkbox is selected, when the button is clicked redirect the user to another page by passing the value of the textarea in the URL.
So that is the logic.
We have three elements.
1)The checkbox
2)The input type button
3) The textarea.
The checkbox is selected, the user clicks on the button and the user goes to another page , and the URL will include the value found in the textarea.
i.e.
http://mydomainname/page.php?ValueThatWasinTextArea=Hello World
Can you help me.
I think it is something simple for a javascript coder.
Thank you so much
$(function(){
$(':button').click(function(){
if($('input[type="checkbox"]').is(":checked")){
window.location.href = "http://mydomainname/page.php?ValueThatWasinTextArea="+ $('textarea').val();
}
});
});
**Of course if there's more than these three elements on the page, you're going to want some more specific selectors
You could subscribe to the submit event of the form and inside test if the checkbox was checked and if yes use window.location.href to redirect to the desired url:
$('#id_of_the_form').submit(function() {
var value = encodeURIComponent($('#id_of_textarea').val());
if ($('#id_of_checkbox').is(':checked')) {
window.location.href = '/page.php?ValueThatWasinTextArea=' + value;
return false;
}
});
If the button is not a submit button you can subscribe for the click event of this button and perform the same logic.
Might be some syntax problem because I code this on top of my head
<input id="myCheckbox" type="checkbox" />
<button id="myButton" onClick="buttonClick" />
<input id="myTextArea" type="textarea" />
<script>
function buttonClick()
{
var checkBox = document.getElementById('myCheckbox');
var textArea = document.getElementById('myTextArea');
if(checkBox.checked)
{
window.location = 'http://mydomainname/page.php?ValueThatWasinTextArea=' + textArea.value;
}
}
</script>
$(document).ready(function() {
$('#btnSubmit').click(function() {
if($('#chkBox').is(':checked')) {
window.location = '/page.php?passedValue=' + $('#txtField').val();
}
});
};
...
<form>
<p>
<input type="checkbox" id="chkBox"> Checkbox</input>
</p>
<p>
<input type="text" id="txtField" value="" />
</p>
<p>
<input type="submit" id="btnSubmit" value="Submit" />
</p>
</form>

Categories

Resources