Adding a specific semantic HTML structure in JS - javascript

can anyone help me adding a specific html structure inside this javascript?
// If question has >1 true answers and is not a select any, use checkboxes; otherwise, radios
var input = '<input id="' + optionId + '" name="' + inputName + '" type="' + inputType + '" /> '
var optionLabel = '<label for="' + optionId + '">' + answer.option + '</label>'
var answerContent = $('<li></li>')
.append(input)
.append(optionLabel)
answerHTML.append(answerContent)
I want to add this HTML structure:
For Radio buttons:
<label class="mdl-radio mdl-js-radio mdl-js-ripple-effect" for="option-1">
<input type="radio" id="option-1" class="mdl-radio__button" name="options" value="1" checked>
<span class="mdl-radio__label">First</span>
</label>
And for checkboxes:
<label class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect" for="checkbox-1">
<input type="checkbox" id="checkbox-1" class="mdl-checkbox__input" checked>
<span class="mdl-checkbox__label">Checkbox</span>
</label>
And here is the part that decide if the input will be a checkbox or a radio button:
// prepare a name for the answer inputs based on the question
var selectAny = question.select_any ? question.select_any : false,
forceCheckbox = question.force_checkbox ? question.force_checkbox : false,
checkbox = (truths > 1 && !selectAny) || forceCheckbox,
inputName = $element.attr('id') + '_question' + (count - 1),
inputType = checkbox ? 'checkbox' : 'radio'
PS: This is my first experience with javascript, i'm a complete newbie on javascript, so.. if anything is missing, tell me

Related

Selecting ID's dynamically in js/ JQuery

I have an html form. Whenever i click add button another copy of it appends. Whenever i click add button, id of my elements increases such as username_0, username_1, username_2... There are 2 radio buttons on my form that whenever i choose second radio button, a hidden textarea appears. Problem is i'm having problem with choosing my dynamic id's of radio buttons. I made a function but its only working for first element since i can't get dynamic id's
<label for="evetKontrol_0">Evet</label>
<input type="radio" id="evetKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygun" checked>
<label for="hayirKontrol_0">Hayır</label>
<input type="radio" id="hayirKontrol_0" name="uygun_0" onclick="javascript:yesnoCheck();" value="uygunDegil">
<div id="ifNo_0" style="visibility:hidden">
<strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_0" name="hayirSebep" style="height: 75px"><br>
</div>
function yesnoCheck() {
if (document.getElementById('evetKontrol_0').checked) {
document.getElementById('ifNo_0').style.visibility = 'hidden';
}
else document.getElementById('ifNo_0').style.visibility = 'visible';
}
I need to be able to get my evetKontrol_#somenumber for my function for every copy of my form.
JSfiddle/ all of my code
I tried to use jQuery( "[attribute*='value']" ) but i couldn't manage to work it out.
Consider the following.
Working Example: https://jsfiddle.net/Twisty/sonvakq2/21/
JavaScript
$(function() {
function addElement(tObj) {
var counter = $("[id^='ogrenci']", tObj).length;
var html = '<div class="col-auto" id="ogrenci_' + counter + '"><label for="ad">Ad</label><input type="text" name="ad[]" class="form-control" id="ad_' + counter + '" placeholder="Öğrencinin Adı"/><label for="soyad">Soyad</label><input type="text" name="soyad[]" class="form-control" id="soyad_' + counter + '" placeholder="Öğrencinin Soyadı"/><label for="no">No</label><input type="text" name="numara[]" class="form-control" id="no_' + counter + '" placeholder="Öğrencinin Numarası"><label for="course">Bölümü</label><input type="text" name="bolum[]" class="form-control" id="course_' + counter + '" placeholder="Öğrencinin Bölümü"><label for="alKredi">Almak İstediği Kredi</label><input type="text" name="alKredi[]" class="form-control" id="alKredi_' + counter + '" placeholder="Almak İstediği Kredi"><label for="verKredi">Alabileceği Kredi</label><input type="text" name="verKredi[]" class="form-control" id="verKredi_' + counter + '" placeholder="Alabileceği Kredi"><label for=""><strong>Uygun mu?</strong> </label><br><label for="evetKontrol_' + counter + '">Evet</label><input type="radio" id="evetKontrol_' + counter + '" name="uygun_' + counter + '" value="uygun" checked><label for="hayirKontrol_' + counter + '">Hayır</label><input type="radio" id="hayirKontrol_' + counter + '" name="uygun_' + counter + '" value="uygunDegil"><div id="ifNo_' + counter + '" style="visibility:hidden"><strong>Uygun Olmama Sebebi:</strong> <input type="textarea" id="hayirSebep_' + counter + '" name="hayirSebep" style="height: 75px"><br></div><div class="input-group-addon"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</div></div>';
tObj.append(html);
}
function showHidden() {
$("[id^='evetKontrol']").each(function(i, el) {
var rel = $("#ifNo_" + i);
if ($(el).is(":checked")) {
rel.show();
} else {
rel.hide();
}
});
}
//add more fields group
$("#add").click(function() {
addElement($("#container"));
});
//remove fields group
$('#container').on('click', "a[id^='remove']", function() {
$(this).parents('div.col-auto').remove();
});
$("#container").on("click", "input[type='radio']", showHidden);
});
Your fiddle wasn't configured properly, so I addressed that first. I moved a lot of the repeatable items into Functions. Switched it all the jQuery and removed any of the local javascript calls.
You can see examples of how to use the Attribute selector in a relative manner to select items you want.
See More: https://api.jquery.com/category/selectors/attribute-selectors/
You shouldn't need to use IDs for this. Just capture the onclick event and pass a boolean to determine if the hidden input should be shown. If you have multiple inputs to show and hide separately, you could pass the ID of the input along with the boolean.
function yesnoCheck(show) {
var ta = document.getElementById('hiddenTA');
if (show) {
ta.style.visibility = 'visible';
} else {
ta.style.visibility = 'hidden';
}
}
<label for="user1_0">User 1</label>
<input type="radio" name="users" id="user1_0" onclick="yesnoCheck(false)" checked />
<label for="user2_0">User 2</label>
<input type="radio" name="users" id="user2_0" onclick="yesnoCheck(true)" />
<input style="visibility:hidden" id="hiddenTA" />
In order to get the evetKontrol_#somenumber, pass that number in the onclick function.
In your JSfiddle, this would mean concatenating the counter variable into the function parameters like
... onclick="javascript:yesnoCheck(' + counter + ');" ...
Then update the function to use that value:
function yesnoCheck(counter) {
if (document.getElementById('evetKontrol_' + counter).checked) {
document.getElementById('ifNo_' + counter).style.visibility = 'hidden';
} else {
document.getElementById('ifNo_' + counter).style.visibility = 'visible';
}

Input text type showing undefined in view source

I have three check box with two is auto selected. I have to display the text field with a label which check box is selected.
I tried below code but it is displaying only one text field and type is undefined I checked in view source. I think there is some issue with this.
Would you help me out?
$(document).ready( function(){
$checkbox=$(".add_student_input").is(":checked");
if($checkbox == true) {
$(".students_items").append('<div class="' + this.id + '"><label>' + $(this).next('label').text() + '</label><input type="' + $(this).data('type') + '" name="input[]" placeholder="' + $(this).next('label').text() + '" class="form-control" /></div>');
} else {
//check false
$('.students_items').find('.' + this.id).remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="checkbox" name="a" id="class_1" class="add_student_input" data-type="text" checked><label for="class_1">number1</label>
<input type="checkbox" name="b" id="class_2" class="add_student_input" data-type="text" checked><label class="class_2">number2</label>
<input type="checkbox" name="c" id="class_3" class="add_student_input" data-type="text"><label class="class_3">number3</label>
<span class="students_items"></span>
You are missing the loop for $(".add_student_input") which gives you three checkboxes. So, you need to use each() that will loop over all three checkbox and check for the checked checkbox and then create a respective text element for it.
$(document).ready( function(){
$checkbox=$(".add_student_input");
$checkbox.each(function(){
var isChecked = $(this).is(":checked");
if(isChecked) {
$(".students_items").append('<div class="' + this.id + '"><label>' + $(this).next('label').text() + '</label><input type="' + $(this).data('type') + '" name="input[]" placeholder="' + $(this).next('label').text() + '" class="form-control" /></div>');
} else {
//check false
$('.students_items').find('.' + this.id).remove();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="a" id="class_1" class="add_student_input" data-type="text" checked><label for="class_1">number1</label>
<input type="checkbox" name="b" id="class_2" class="add_student_input" data-type="text" checked><label class="class_2">number2</label>
<input type="checkbox" name="c" id="class_3" class="add_student_input" data-type="text"><label class="class_3">number3</label>
<div class='students_items'></div>
It appears that you do not have HTML element with class "students_items" in your code, so this portion of the JavaScript will not be executed:
$(".students_items").append('<div class=....)
Create element with such CSS class and try again.

html js append and getElementByName

Why i can't getElementByName?
<form class="form" action="#">
<p class="EmptySlot" hidden>
<input name="characters" type="radio" id="empty" disabled="disabled"/>
<label for="empty">Пустой слот</label>
</p>
</form>
Then:
$(".form").append('\
<p>\
<input name="character" type="radio" id="' + notformatname + '" value="' + notformatname + '"/>\
<label for="' + notformatname + '" id="charlabel">' + formatname + '</label>\
</p>');
And it's don't work:
var radios = document.getElementsByName('character');
The method will return a collection, not a single Element. You may try...
$(".form")[0].append('\
<p>\
<input name="character" type="radio" id="' + notformatname + '" value="' + notformatname + '"/>\
<label for="' + notformatname + '" id="charlabel">' + formatname + '</label>\
</p>');
Should get the first form that belongs to the "form" class.
The second should work, but remember that "radios" will be a collection too.
.getElementsByName might return more than one element if multiple elements have the name of 'character'.
To get the first item in the list of returned elements, try:
var radios = document.getElementsByName('character')[0];

Output in Textarea from User Input

PROBLEM SOLVED
I just started learning JavaScript, and I came across a problem while coding a quick tool for a game that I play. I want users to be able to input a couple of things via an HTML Form and I want the JS Script to take that input and turn it into an SQL.
Here is my HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>HabSQL - Online SQL Generator</title>
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link href="css/styles.css" rel='stylesheet' type='text/css'>
</head>
<body>
<header>Welcome to HabSQL v1.0! The Online Habbo SQL Generator!</header>
<p>HabSQL is strictly for use with Habbo Furniture SQLs and Data. Please enter all necessary information accordingly.</p>
<script src="scripts/habSQL.js"></script>
<form action="javascript:void(habSQL())">
<fieldset>
Furniture Name: <input id="furniName" type="text">
Furniture ID: <input id="furniID" type="number"><br>
SWF File Name: <input id="fileName" type="text"> (Exclude .SWF)<br>
Sprite ID: <input id="spriteID" type="number"> (We recommend that you use the same ID as Furniture ID).
</fieldset>
<fieldset>
Furniture Type: <input id="furniType" type="radio" value="s" name="furniType">Floor <input id="furniType" type="radio" value="i" name="furniType">Wall <input id="furniType" type="radio" value="e" name="furniType">Effect<br>
</fieldset>
<fieldset>
Furniture Width: <input id="furniWidth" type="number" class="dimensions"> Furniture Length: <input id="furniLength" type="number" class="dimensions"> Furniture Height: <input id="furniHeight" type="number" class="dimensions"><br>
Can you stack furniture on it? <input id="canStack" type="radio" value="1" name="canStack">Yes <input id="canStack" type="radio" value="0" name="canStack">No<br>
Can you sit on it? <input id="canSit" type="radio" value="1" name="canSit">Yes <input id="canSit" type="radio" value="0" name="canSit">No<br>
Can you walk on/through it? <input id="canWalk" type="radio" value="1" name="canWalk">Yes <input id="canWalk" type="radio" value="0" name="canWalk">No<br>
Can you recycle it? <input id="canRecycle" type="radio" value="1" name="canRecycle">Yes <input id="canRecycle" type="radio" value="0" name="canRecycle">No<br>
Can you trade it? <input id="canTrade" type="radio" value="1" name="canTrade">Yes <input id="canTrade" type="radio" value="0" name="canTrade">No<br>
Can you sell it on the Marketplace? <input id="canSell" type="radio" value="1" name="canSell">Yes <input id="canSell" type="radio" value="0" name="canSell">No<br>
Can you give it to someone as a gift? <input id="canGive" type="radio" value="1" name="canGive">Yes <input id="canGive" type="radio" value="0" name="canGive">No<br>
Can you stack it in the inventory? <input id="invStack" type="radio" value="1" name="invStack">Yes <input id="invStack" type="radio" value="0" name="invStack">No<br>
</fieldset>
<fieldset>
Interaction Type:<br>
<input id="intType" type="radio" value="default" name="intType">None<br>
<input id="intType" type="radio" value="bed" name="intType">Bed<br>
<input id="intType" type="radio" value="vendingmachine" name="intType">Vending Machine<br>
<input id="intType" type="radio" value="trophy" name="intType">Trophy<br>
<input id="intType" type="radio" value="gate" name="intType">Gate<br>
<input id="intType" type="radio" value="onewaygate" name="intType">One Way Gate<br>
<input id="intType" type="radio" value="dice" name="intType">Dice<br>
<input id="intType" type="radio" value="teleport" name="intType">Teleporter<br>
(More Interaction Types Coming in v2.0)<br>
</fieldset>
<fieldset>
How many interactions does the furniture have? (i.e. a dice has 6 sides and a closed side, therefore 7 interactions.)<br>
<input id="intCount" type="number"><br>
If your furniture gives out an item, what is the item's ID? 0, if none. (View external_flash_texts.txt or external_flash_texts.xml for ID #'s.)<br>
<input id="vendingID" type="number"><br>
</fieldset>
<input type="Submit" value="Generate!">
</form>
Furniture SQL:<br>
<textarea id="furniSQL" readonly="true" rows="10" cols="50"></textarea>
</body>
</html>
And here is my JS:
// HabSQL - Online Habbo SQL Generator
// Developed by Thomas Yamakaitis - March 3, 2015
function habSQL() {
var furniID = document.getElementById('furniID').value;
var furniName = document.getElementById('furniName').value;
var fileName = document.getElementById('fileName').value;
var furniType = document.getElementById('furniType').value;
var furniWidth = document.getElementById('furniWidth').value;
var furniLength = document.getElementById('furniLength').value;
var furniHeight = document.getElementById('furniHeight').value;
var canStack = document.getElementById('canStack').value;
var canSit = document.getElementById('canSit').value;
var canWalk = document.getElementById('canWalk').value;
var spriteID = document.getElementById('spriteID').value;
var canRecycle = document.getElementById('canRecycle').value;
var canTrade = document.getElementById('canTrade').value;
var canSell = document.getElementById('canSell').value;
var canGive = document.getElementById('canGive').value;
var invStack = document.getElementById('invStack').value;
var intType = document.getElementById('intType').value;
var intCount = document.getElementById('intCount').value;
var vendingID = document.getElementById('vendingID').value;
var comma = ", ";
var commaQuotes = "', '";
var quoteComma = "', ";
var commaQuote = ", '";
document.getElementById('furniSQL').innerHTML = "INSERT INTO `furniture` (`id`, `public_name`, `item_name`, `type`, `width`, `length`, `stack_height`, `can_stack`, `can_sit`, `is_walkable`, `sprite_id`, `allow_recycle`, `allow_trade`, `allow_marketplace_sell`, `allow_gift`, `allow_inventory_stack`, `interaction_type`, `interaction_modes_count`, `vending_ids`, `is_arrow`, `foot_figure`, `height_adjustable`, `effectM`, `effectF`, `HeightOverride`) VALUES (" + furniId + commaQuote + furniName + commaQuotes + fileName + commaQuotes + furniType + quoteComma + furniWidth + comma + furniLength + comma + furniHeight + commaQuote + canStack + commaQuotes + canSit + commaQuotes + canWalk + quoteComma + spriteID + commaQuote + canRecycle + commaQuotes + canTrade + commaQuotes + canSell + commaQuotes + canGive + commaQuotes + invStack + commaQuotes + intType + quoteComma + intCount + comma + vendingID + ");";
}
I can't seem to pinpoint exactly what it is that I am doing wrong. If somebody could please assist me, that would be greatly appreciated.
Thanks!
Thanks to a few users here! The solution was a typo and I believe it was also value instead of innerHTML too.
A simple typo: furniId instead of furniID on the last line
JavaScript is case-sensitive so if you capitalize a variable name differently it's a completely different variable, and so it does not know what you mean.
You got a typo: furniID in your last element which is document.getElementById('furniSQL').value= is spelled as furniId
Textareas are modified by value, not innerHTML
so set it up to
document.getElementById('furniSQL').value = "INSERT INTO `furniture` (`id`, `public_name`, `item_name`, `type`, `width`, `length`, `stack_height`, `can_stack`, `can_sit`, `is_walkable`, `sprite_id`, `allow_recycle`, `allow_trade`, `allow_marketplace_sell`, `allow_gift`, `allow_inventory_stack`, `interaction_type`, `interaction_modes_count`, `vending_ids`, `is_arrow`, `foot_figure`, `height_adjustable`, `effectM`, `effectF`, `HeightOverride`) VALUES (" + furniId + commaQuote + furniName + commaQuotes + fileName + commaQuotes + furniType + quoteComma + furniWidth + comma + furniLength + comma + furniHeight + commaQuote + canStack + commaQuotes + canSit + commaQuotes + canWalk + quoteComma + spriteID + commaQuote + canRecycle + commaQuotes + canTrade + commaQuotes + canSell + commaQuotes + canGive + commaQuotes + invStack + commaQuotes + intType + quoteComma + intCount + comma + vendingID + ");";
and you should be good to go.

radio button how to pre select value with the value determined in the function

I have a method like:
$('.officeapprovalspan').click(function () {
var invoicelineid = $(this).data("invoicelineid");
var approval = $(this).data("approval");
$(this).replaceWith('<input type="radio" name="variety" value="null" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="pleaseapprove">Please Accept</span><br >' +
'<input type="radio" name="variety" value="false" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="onhold">On Hold</span><br >' +
'<input type="radio" name="variety" value="true" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="accepted">Accepted</span>');
$(document).on('change', '.radioapproval', radiohandler);
});
So, I have the three radio buttons. What I want to achieve is based on the value of the variable approval preselect the appropriate radio button. Approval will have the value null, false or true.
Can someone please tell me how you would write this given I'm adding it with the replaceWith
Try using .html():
var invoicelineid = $(this).data("invoicelineid");
var approval = $(this).data("approval");
$(this).html(
'<input type="radio" name="variety" value="null" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="pleaseapprove">Please Accept</span><br >' +
'<input type="radio" name="variety" value="false" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="onhold">On Hold</span><br >' +
'<input type="radio" name="variety" value="true" class="radioapproval" data-invoicelineid=' + invoicelineid + ' /><span class="accepted">Accepted</span>'
)
.find(':radio[name="variety"][value="' + approval + '"]')
.prop('checked', true);
For example if the value of the approval variable is true the last radio button will be selected.

Categories