So I'm working on a JS project for school where I have a form in which the user enters the amount of forces in a problem, once entered a loop will created new fields per force. I have that part down, but I am having an issue with storing the text input from each of these new fields. I am using the .on function where the user has to click a button and then based on the id of the button clicked a number for the force array is created. The input is then suppose to be read into the array, but its just not working and its driving me nuts. Any ideas? Thanks in advance.
function forceRecording(numofforces){
for(var i =0; i<numofforces; i++){
$('#button1').after("<tr><td>Force DFO " + i +":</td><td><form><input type='text' name='lengthMeasure_'/></form></td><td><div class='button' id='lengthButton_"+i+"'>Add!</div></td></tr>")
$('#button2').after("<tr><td>Force " + i +":</td><td><form><input type='text' name='forceMeasure_'/></form></td><td><div class='button' id='forceButton_"+i+"'>Add!</div></td></tr>")
}
};
$("button[id^='forceButton']").on("click",function(){
var num = parseInt($(this).attr("id").split("_")[1]);
forces[num] = $('input[id=forceMeasure_'+num+']').val();
$('#button1').after('<td>'+forces[num]+'</td>');
});
As you can see I'm adding another column in my table temporarily just to check if the force is actually point into the array but when I run this, nothing new pops up.
I am pretty sure you would have solved this issue by now. But I just happened to come across this post and thought that an answer could help future readers.
There were three issues in your code which prevented it from working and they are as follows:
$("button[id^='forceButton']") is used instead of $(".button[id^='forceButton']"). Note the . before button. Without the . jQuery would look for a button tag with id like forceButton whereas the tag in question was a div with class as button.
$('input[id=forceMeasure_'+num+']').val(); is used to get the text box value but your input field doesn't have any id. It only has a name, so instead use $('input[name=forceMeasure_' + num + ']').val();.
The input field is set as <input type='text' name='forceMeasure_'/>. Note that the count part after the forceMeasure_ is missing. It should have been <input type='text' name='forceMeasure_" + i + "'/>.
Making all the three changes as mentioned above, the code works fine.
Click here for a sample demo of the working code.
Related
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)
})
I am pretty new to coding php and javascript but have manged to scrape my way through so far. However, I have hit a wall. I'm not 100% sure that what I'm trying to do can be done, or that I'm even attempting it in an effective way.
I have a dynamically filled table, made of rows from a SQL statement using php. On each row is a radio button, each one given a unique value based on the row number (a unique value in one of the database columns). I am attempting to program a button that enables the user to pass a selected radio button value to a separate php enabled page that will allow the user to edit the row information using the unique row value. Also, i used the confirm option, because I would also like to add an if else statement that allows the user to cancel, if the wrong row was selected (I haven't attempted that yet because I haven't been able to get the value to pass).
Page button
<input type="button" id="edit_order_button" value="Edit Order"></input>
JQuery page
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
var r = confirm("Confirm Order Number to edit: " + selected);
$.post("php/editOrder.php", {
selected1: selected
}, function(data,status) {
//alert("Data: " + data + "\nStatus: " + status);
window.open("php/editOrder.php","Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
});
});
});
PHP end destination
<?php
//Login to database (usually this is stored in a separate php file and included in each file where required)
require('config.php');
$selected2= isset($_POST['selected1']) ? $_POST['selected1'] : ''; // Fetching Values from URL
echo "Selected Row number is ".$selected2.".";
mysqli_close($connection); // Connection Closed.
?>
I have tried a few things but have so far been unsuccessful in getting the new window to load with the value of the radio button passed. Currently, the window loads, but the new window only displays the echo text, no variable. When I run with the alert popup, the data shows me the value of the selected row but it does not seem to be posting to the new page prior to the window.open command. Any tips would be appreciated, or if i'm approaching the problem from a wrong angle, any insights would also be great. I have also tried debugging, thinking I was missing a parentheses or semicolon but I wasn't able to find anything. Thanks
Looks to me like you can get rid of the post statement altogether and just pass the selection to the newly opened window.
$(document).ready(function(){
$("#edit_order_button").click(function(){
var selected = $("input[name ='order_edit_select']:checked").val();
// only open window if order okayed
if ( confirm("Confirm Order Number to edit: " + selected) ) {
window.open("php/editOrder.php?selected1=" + selected,"Edit Order","menubar=1,resizable=1,width=750,height=600, left=250, top=50");
}
});
});
php/editOrder.php:
$selected2 = $_GET['selected1'];
echo "Selected Row number is $selected2.";
Here's the function that checks if the form is complete.
So, what I'm trying to do:
If radio is not selected, throw a message.
If radio is "yes", but text is not entered, throw error.
If radio is "no" but text is entered, make the text empty.
If all is good, add stuff into `allResponses
The form was displayed 5 times, and input was as follows:
Yes a1
No
Yes a3
No
Yes
Now, this input should display an error since in 5th case, "yes" is selected but nothing is entered in the textbox.
However, I get this:
http://i.imgur.com/ya2CUp0.png
Also, the text is not being updated as in 1st and 3rd cases.
I don't know a lot about JS, so please provide me with as explained responses as you can.
EDIT: Complete code: http://pastebin.com/scNSNM2H
Thanks
You have this in a loop:
var exaggerationPart = document.getElementById('exaggeration').value
And then you check to make sure it has a value for each item. But you will get the same value each time.
You are creating multiple inputs with the same id, "exaggeration". This is invalid HTML. Id's must be unique. To correct this, you can increment the id the same as you are doing with other elements (such as, input[name='response"+thisJokeIndex+"']).
var exaggerationPart = document.getElementById('exaggeration' + thisJokeIndex).value
tipTD2.append("<input type='text' name='exaggeration' id='exaggeration" + tipIndex + "' size='70'>")
Working demo: jsfiddle.net/svvge/2
Edit: To clear the value of the text box, you must change the value property of the text box element. Right now you are just changing the value of a variable.
var exaggerationInput = document.getElementById('exaggeration' + thisJokeIndex).value;
var exaggerationPart = exaggerationInput.value;
exaggerationInput.value = '';
I'm very new to jQuery and have been stumped by particular issue. I am dynamically adding 2 checkbox fields to a screen form using the code below:
var summon_search = "<br><br><br><label for='summon_search'>Search this resource from compatible products*</label><input type='checkbox' id='summon_search' >";
var summon_link = "<br><br><label for='summon_link'>Link direct from content items in compatible products*</label><input type='checkbox' name='summon_link'>";
$(summon_search+summon_link).insertAfter("#jstor_selection");
However I have had limited success when I want to remove these fields AND labels (which is dependant on another value) and replace them with new fields. The code below shows my best attempt so far. It does appear to remove the labels and first field, but for some reason the last field remains. Could someone please advise if they can spot anything I've done wrong, or perhaps supply a better example of handling this ?
if ($("#summon_search").length > 0 ) {
//Removal of Label and Field (Attempted)
$("label[for=summon_search]").remove();
$("label[for=summon_link]").remove();
$("#summon_search").remove();
$("#summon_link").remove();
Any feedback much appreciated.
Change name='summon_link' to id='summon_link', because #summon_link expects an id.
if you see your code the summon_link variable give it a id instead of name like in the summon_search variable
name=summon_link change it to id='summon_link'
if your intention is to add these HTML string after object with Id 'jstor_selection', you can use like this
$("#jstor_selection").append(summon_search+summon_link);
you should give the for= value in quotes.
EDIT: to remove extra <br>, normally it is suggested not to use <br>
$("label[for='summon_search']").prev('br').remove()
$("label[for='summon_link']").prev('br').remove()
$("label[for='summon_search']").remove();
$("label[for='summon_link']").remove();
also in the suman_link input element you have given as name
<input type='checkbox' name='summon_link'>
either change this to
<input type='checkbox' id='summon_link'/>
or
$("#summon_link").remove();
to
$("input[name='summon_link']").remove();
I have just begun playing with MooTools, and I don't understand why the following happens:
var input = new Element('input');
input.set('type','text');
input.set('value','this is the value');
console.log(input);
results in: <input type="text">, so setting the value hasn't worked.
But if I do this:
var input = new Element('input');
input.set('type','text');
input.set('someValue','this is the value');
console.log(input);
I get the expected result of <input type="text" somevalue="this is the value">.
Am I overlooking something, is what I am trying to do not allowed, is this a bug in Chrome (11.0.696.71, OS X) or am I doing something else wrong?
Update: thanks for your answer! You are right, the value is actually being set; console.log(input.get('value')) gives back the proper value and I can see the value in the input field when I append the input object to the DOM.
Apparently, the value setting is just not reflected as an attribute of the HTML element, but only stored internally.
Are you sure the value isn't being set?
What do you get when you call: input.get('value')
I tested this (in firefox) and even though the console just logs <input type="text"> the value does in fact get set. Try adding the element to the page and you'll see it :)
I've had a similar problem with this 'red herring' which I've since solved, and thought I'd share.
I'm trying to make certain cells of a table row editable when the user clicks on the row:
var cells = this.getElements("td");
for (var ix=0;ix<cells.length; ix++){
if (cells[ix].hasClass("edType_text")){
var celltext = cells[ix].get("text");
cells[ix].set('text','');
var editTag = new Element ('input',{type:'text','value':celltext});
editTag.inject(cells[ix]);
}
}
This seemed to work OK but when I clicked on the cell I couldn't edit it. Firebug and Chrome tools showed the added input tag as
<input type='text'>
instead of the expected:
<input type='text' value='xxxxxx' />
However this is perfectly normal as commented on above.
Spotted the 'deliberate' error ?
Of course when I clicked on the input field it triggered the mouse event on the row again, thus preventing me getting at the input!!!! :-{
To avoid this just add this line of code at the end of the if block:
editTag.addEvent("mousedown",function(event){event.stopPropagation();});