I have the following, which shows upcoming matches and allow users to vote who will win
Team names and fixtures are dynamically pulled from db, it is unlikely that number of matches will be the same for each round, thus nr matches vary for each round.
When user made his selection before he clicks submit, I would like to display something like:
You have selected:
Force (Selected) To Win Crusaders(not selected)
Highlanders (Selected) To Win Cheetahs(not selected)
:
I got this working correctly like so:
But Im stuggling to put the "VS" part team not selected in the string. I.E it is easy enough to put the selected teams value in the string but im struggling to get the name from team not selected.
Perhaps this fiddle will give you a better idea to what im trying to achieve:
https://jsfiddle.net/timcoetzee/L9gna8a0/3/
function handleClick() {
// Get all the inputs.
var inputs = makePicks.elements;
var radios = [];
//Loop and find only the Radios
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type == 'radio') {
radios.push(inputs[i]);
}
}
myradiovalue = "";
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
if (myradiovalue == "") myradiovalue = radios[i].value
else myradiovalue = myradiovalue + ", " + radios[i].value
}
}
document.getElementById("dispPicks").innerHTML = "YOU HAVE SELECTED " + myradiovalue;
return false;
}
<form name="makePicks">
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks1" value="Chiefs"><span>Chiefs</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks1" value="Hurricanes"><span>'Hurricanes'</span>
</label>
<label class="pink">
<input type="radio" name="picks1" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
<label class="green">
<input type="radio" id="x" onclick="handleClick()" name="picks2" value="Lions"><span>Lions</span>
</label>
<label class="yellow">
<input type="radio" onclick="handleClick()" name="picks2" value="Stormers"><span>'Stormers'</span>
</label>
<label class="pink">
<input type="radio" name="picks2" value="draw" onclick="handleClick()"><span>Draw</span>
</label>
<br />
</form>
<div id="dispPicks"></div>
Any help or advise very much appreciated
function ff() {
var msg = "you have selected:<br/>" ;
var radios = makePicks.querySelectorAll('input[type=radio]');
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked) {
msg += getMessage(radios[i].getAttribute('name')) + "<br/>";
}
}
document.getElementById("dispPicks").innerHTML = msg;
}
function getMessage(nm) {
var rds = makePicks.querySelectorAll('input[type=radio][name=' + nm + ']');
var checked = 0;
for(var i = 0; i < rds.length; i++) {
if(rds[i].checked)
checked = i;
}
if(checked == 2)
return rds[0].value + " (not selected) to draw " + rds[1].value + " (not selected)";
else if(checked == 1)
return "<b>" + rds[1].value + "</b> (selected) to win " + rds[0].value + " (not selected)";
else
return "<b>" + rds[0].value + "</b> (selected) to win " + rds[1].value + " (not selected)";
}
jsfiddle DEMO
Related
I am trying to use .on to listen for an event.
html:
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name ="name1"><br>
</div>
JS:
for (n = 1; n < inputLength+3 ; ++n) {
var test2 = document.getElementById(dude+n);
$(test2).on('change', '#group_names', forFunction);
}
The change to the input field is not being recognized.
Additionally, I am hoping .on will recognize changes made to new html i am injecting using the following function:
var dude = "name";
function forFunction() {
for (m = 1; m < inputLength + 1; ++m) {
var test = document.getElementById(dude + m)
if (test.value != "") {
var txt = "<input type=\"text\" class=\"form-control name\" placeholder=" + dude + (m + 1) + " id=" + dude + (m + 1) + " name=" + dude + (m + 1) + "><br>";
document.getElementById('group_names').insertAdjacentHTML('beforeend', txt);
//function updateHTML(txt)
}
}
}
I am not sure if my syntax for .on is correct. I am trying to use "#group_names" as the selector, but not sure if I am doing it right.
Thanks
You probably want to use event delegation on the parent div instead.
$('#group_names').on('change', 'input.form-control.name', forFunction);
Consider the following jQuery code.
$(function() {
var inputFields = $("input[id*='name']");
function forFunction(evt) {
console.log(evt.type);
inputFields.each(function(i, el) {
var n = i + 1;
if ($(el).val() != "") {
console.log("Value Detected");
$("<input>", {
type: "text",
class: "form-control name",
placeholder: "group" + n,
id: "group" + n,
name: "group" + n
}).insertBefore("#group_names");
}
});
}
inputFields.on("change", forFunction);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group" id="group_names">
<label> Names: </label><br>
<input type="text" class="form-control name" placeholder="name1" id="name1" name="name1"><br>
</div>
This should work for all of the Input items.
I have a page which prompts the user to enter a positive integer from 1 to 9, then the javascript code will generate a multiplication table from the input value all the way to 9. I am getting an error in which I cannot retrieve the value and do a multiplication with it.
function timesTable()
{
var values = document.getElementById('value1');
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
Expected result:
You have to take the value of the element not the element itself
var values = document.getElementById('value1').value;
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
You are trying to multiply the element itself. What you actually want is the value.
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<9; i++) {
showTables += values + " x " + i +" = "+ values*i + "\n";
}
var p_tables = document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="text" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
the javascript line in which you are trying to find value, is wrong as it will return the whole DOM and it's attributes and property.
You just have to find it's value, replace you line
var values = document.getElementById('value1');
with
var values = document.getElementById('value1').value;
This does what you want.
Note that if the user enters something unexpected, it may still fail. You can use an input of type="number" to require an integer (at least in some browsers.)
const userValue = document.getElementById("value1").value;
const p_tables = document.getElementById("tables");
let outputHtml = "";
for(let i = 1; i < 10; i++){
outputHtml += userValue + " x " + i + " = " + userValue * i + "<br/>";
}
p_tables.innerHTML = outputHtml;
you are using input field as text for table generation its better to use Number as input type and to get the value of input field you have to use value function as used in above code and for line break use
<\br>(please ignore '\').
function timesTable()
{
var values = document.getElementById('value1').value;
var showTables = '';
for (var i=1; i<=9; i++) {
showTables += values + " x " + i +" = "+ values*i + "<br>";
}
document.getElementById('tables').innerHTML = showTables;
}
<label>Enter an integer from 1 to 9 : </label>
<input type="Number" size=20 id=value1 name="value">
<button onclick="timesTable()">Generate times table</button><br> <br>
<p id="tables"></p>
I want to capture the values of a form to elaborate them in some function before to record them in the DB. I think I should use JavaScript so here we are:
My model:
class Region(models.Model):
number = models.CommaSeparatedIntegerField(max_length=9, unique=True)
city = models.OneToOneField(Community, blank= True, null=True)
resources = models.ManyToManyField(Resource, blank=True)
My form:
class Crea_RegionForm(forms.ModelForm):
quantity = forms.IntegerField(initial=1)
resources=MyModelMultipleChoiceField(Resource.objects.all(),
widget=forms.CheckboxSelectMultiple, label='Risorse')
class Meta:
model = Region
fields = ('number', 'city', 'resources')
def __init__(self, *args, **kwargs):
super(Crea_RegionForm, self).__init__(*args, **kwargs)
quantity = self.fields['quantity'] #costum field
My MyModelMultipleChoiceField:
class MyModelMultipleChoiceField(forms.ModelMultipleChoiceField):
def label_from_instance(self, obj):
return format_html(
'<span style="font-weight:normal">{}</span>', obj.name)
So the html for resources in my page:
Risorse
<ul id="id_resources">
<li>
<label for="id_resources_0">
<input id="id_resources_0" name="resources" type="checkbox" value="1" />
<span style="font-weight:normal">Turism</span>
</label>
</li>
<li>
<label for="id_resources_1">
<input id="id_resources_1" name="resources" type="checkbox" value="2" />
<span style="font-weight:normal">Agricole</span>
</label>
</li>
<li>
#others
</li>
</ul>
and finally my javascript in crea_region.html:
<input type="button" value="Create" id="CreateButton" />
<script type="text/javascript">
<!--
var myform = document.getElementById("crea_region_form");
var number = myform.number.value;
var city_index = document.getElementById("id_city").selectedIndex;
var city;
if (city_index > -1) {
city = document.getElementById("id_city").options[city_index].text;
document.write("city: " + city);
}
var risorse = myform.resources;
var selectedresources = [];
for (var i = 0; i < risorse.length; i++) {
document.write("risorse: " + risorse[i].text);
//document.write("risorse: " + risorse[i].value);
if (risorse[i].selected) selectedresources.push(risorse[i].value);
}
document.write("risorse: " + selectedresources);
var quantity = myform.quantity.value;
var button = document.getElementById("CreateButton");
// to be completed
//-->
</script>
The problem is in resources: a costum ModelMultipleChoiceField that create a list of checkbox. My script can't read the textual and the lines
document.write("risorse: " + risorse[i].text) give=> risorse: undefined
document.write("risorse: " + risorse[i].value) give=> risorse: 1
document.write("risorse: " + selectedresources) give=> risorse:
EDIT
My new script:
...
var risorse = myform.resources;
document.write("risorse: " + risorse[1].nextSibling.innerHTML)
console.log(risorse)
console.log(risorse[1].nextSibling.innerHTML)
var selectedresources = [];
for (var i = 0; i < risorse.length; i++) {
document.write("risorse: " + risorse[i].nextSibling.innerHTML);
if (risorse[i].selected) selectedresources.push(risorse[i].nextSibling.innerHTML);
}
document.write("risorse: " + selectedresources);
document.write("risorse: " + risorse[1].nextSibling.innerHTML) give=> undefined
console.log(risorse) give => RadioNodeList [ <input#id_resources_0>, <input#id_resources_1>, <input#id_resources_2>, <input#id_resources_3>, <input#id_resources_4>, <input#id_resources_5>, <input#id_resources_6>, <input#id_resources_7> ]
console.log(risorse[1].nextSibling.innerHTML) give=> undefined
Sorry, but checkbox doesn't have a text attribute, according to this link, the only attributes are: checked, name, required, value.
You will need to update your code, probably have an object somewhere in your app with key=>text so you can find the text that correspond to specific key, something like this:
var _texts = {'1': 'Text 1', '2': 'Text 2'};
var risorse = myform.resources;
for (var i = 0; i < risorse.length; i++) {
document.write("risorse: " + _texts[risorse[i].value]);
}
Fill free to validate if risorse[i].value exist in texts, you can use the hasOwnProperty function.
Or, you can take advantage of you current html and use the nextSibling:
var risorse = myform.resources;
for (var i = 0; i < risorse.length; i++) {
document.write("risorse: " + risorse[i].nextSibling.innerHTML);
}
Done!! This look working...
My script:
...
var risorse = myform.resources;
var selectedresources = [];
for (var i = 0; i < risorse.length; i++) {
if (risorse[i].checked) selectedresources.push(risorse[i].nextSibling.nextSibling.innerHTML);
}
document.write("risorse: " + selectedresources);
So I have this javascript code below. I am trying to make it so whenever the user hits cancel on the confirmation box. The previous selected option they have selected becomes reselected. Another option instead of the previous, is if we could have it select option 2 based on value ' A' instead of my current way of selecting option 2 based on the array of radio names.
<script type="text/javascript">
function confirmUnschedule() {
var checked = false;
var element = "";
var inputs = document.getElementsByName('Acceptance');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = true;
element = inputs[i];
break;
}
}
if(checked==true){
if (!confirm('Scheduling will be undone if you change the rating. Are you Sure?')){
inputs[1].checked=true;
};
};
}
</script>
<input type='radio' name='Acceptance' value=' ' checked='checked' onclick='confirmUnschedule()'>option 1
<br/>
<input type='radio' name='Acceptance' value=' A' onclick='confirmUnschedule()'>option 2
<br/>
<input type='radio' name='Acceptance' value=' R' onclick='confirmUnschedule()'>option 3
<br/>
If you let your function return false, the event is aborted and the radio button group returns to previous state.
Edit: use return in the onclick attribute as well.
Html
<input type='radio' name='Acceptance' value=' ' checked='checked' onclick='return confirmUnschedule();'>option 1
<br/>
<input type='radio' name='Acceptance' value=' A' onclick='return confirmUnschedule();'>option 2
<br/>
<input type='radio' name='Acceptance' value=' R' onclick='return confirmUnschedule();'>option 3
<br/>
Javascript
function confirmUnschedule() {
var checked = false;
var element = "";
var inputs = document.getElementsByName('Acceptance');
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].checked) {
checked = true;
element = inputs[i];
break;
}
}
if (checked === true) {
if (!confirm('Scheduling will be undone if you change the rating. Are you Sure?')) {
return false;
}
}
}
jsFiddle = http://jsfiddle.net/ahsjoe0x/
I have this code for multi check-box
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
jQuery/JavaScript:
myArray1 = new Array(
"1","2","3","4","5","6"
);
$("#ZIBI").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
$("#ZIBI").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
$('#ZIBI').trigger('create');
how to check all or uncheck all by pressing any button ?
thanks
In this JsFiddle you'll find a method to check/uncheck all checkboxes within a given div, using a checkbox with id _main:
function checkAll(e){
e = e || event;
var from = e.target || e.srcElement
,cbs = this.querySelectorAll('input'), i=1;
if (/^_main$/i.test(from.id)){
for (;i<cbs.length;i+=1){
cbs[i].checked = from.checked;
}
} else {
var main = document.querySelector('#_main')
,j = cbs.length;
for (;i<cbs.length;i+=1){
j -= cbs[i].checked ? 0 : 1;
}
main.checked = j === cbs.length ? true : false;
}
}
Update
New elements should be added to $(".selector").controlgroup("container") not $(".selector") directly. If you add them to main div, elements won't be styled as a _controlgroup`.
You need to refresh .checkboxradio("refresh") checkbox or radio to apply jQM styles. Another point, .trigger("create") is deprecated as of jQM 1.4 and replaced with .enhanceWithin().
myArray1 = new Array(
"1", "2", "3", "4", "5", "6");
/* remove previous elements */
$("#ZIBI").controlgroup("container").html('');
for (var i = 0; i < myArray1.length; i++) {
row = myArray1[i];
/* add new ones to container */
$("#ZIBI").controlgroup("container").append(
'<label for=' + row + '>' + row + '</label>' +
'<input type="checkbox" name="favcolor" id=' + row + ' value=' + row + '>');
}
/* refresh controlgroup and enhance elements within */
$("#ZIBI").controlgroup().enhanceWithin();
/* check/uncheck on button click */
$("#foo").on("click", function () {
var status = $("#ZIBI [type=checkbox]").eq(0).prop("checked") ? false : true;
$("#ZIBI [type=checkbox]").prop("checked", status).checkboxradio("refresh");
});
Demo
You can try this:
HTML:
<fieldset data-role="collapsible">
<legend>Pick one</legend>
<div data-role="controlgroup" id="ZIBI" align="right" >
</div>
</fieldset>
<input type="checkbox" id="all" value="Toggle" />
jQuery:
$('#all').on('click', function() {
if(this.checked) {
$('#ZIBI').find('input[type=checkbox]').prop('checked', true);
} else {
$('#ZIBI').find('input[type=checkbox]').prop('checked', false);
}
});
Working Fiddle.