Creating a Pass Fail Input Function - javascript

I am creating a test form. I have created a form with a list of steps to test.
Instead of every item on the list needing:
<input type="radio" name="step1">Pass<input type="radio" name="step1">Fail
I wanted to create a function so I could just call it every time to create it.
This is my function so far:
function createPassFail(name)
{
var Pass = document.createElement('input');
Pass.type = "radio";
Pass.name = name;
document.getElementById("Pass").innerHTML = "Pass";
var Fail = document.createElement('input');
Fail.type = "radio";
Fail.name = name;
document.getElementById("Fail").innerHTML = "Fail";
}
And then I call it with:
<li>Step One: Turn the TV On
<input id = "step1" onload="createPassFail(this.value)">
</li>
All this does is create a textbox which is not what I was going for. I am also not sure if onload is correct.

Instead of passing in the value to the function you should pass the id:
onload="createPassFail(this.id)"
// ^^
I say your event should be onblur because I don't think onload is the event handler you should be using. You can use my suggestion or maybe set up a button next to the text box which, when clicked (using onclick) does what you want.
Moreover, you haven't inserted the pass or fail elements into HTML. Try this:
document.body.appendChild(Pass);
document.body.appendChild(Fail);
This inserts the newly-created elements directly to the end of the body element. If you would like them to be child to some element therein, you would have to access the element with a suitable method. For example, with getElementById:
document.getElementById( element ).appendChild(Pass); // do the same for Fail
However, this can all be easily done with jQuery.
$(document).ready(function() {
function createPassFail(name)
{
$('body').append('<input type="radio" id="' + name + '">Pass');
$('body').append('<input type="radio" id="' + name + '">Fail');
}
$('#step1').ready(function() {
createPassFail(this.id);
});
});
Live Demo

Related

How to hide certain characters within an html input list?

I have an html input list, with an associated datalist, defined as follows:
<input list="mylist" id="my-input" name="friend-name"
placeholder="Begin typing friend's name here..."
required class="form-control">
The list itself (and the associated datalist) is working fine. However, each of my entries are of the form: "String [numeric_id]"
What I am wondering is if there is any way that I can somehow hide
the [numeric_id] part before the form is submitted.
I have looked at the pattern attribute, but that seems to limit the
actual data allowed in the input, which isn't what I want - I just
want the part between square brackets [] to be hidden, but still
submitted to the form.
It would be ok to move it to another input of type=hidden as well.
Is there any possible way to do that?
#isherwood, here is my form tag:
<form action="/chat_forwarding/modal_edit_msg.php" id="fwd-form" method="POST" class="form-inline" style="display: block;">
If you're not using any framework that support binding, you should listen to input events and update a hidden input based on that.
This is a function that may give you the idea:
let realInput = document.getElementById('real-input');
let userInput = document.getElementById('user-input');
userInput.addEventListener('input', function(value) {
const inputValue = value.target.value;
realInput.value = inputValue; // update the hidden input
const userInputResult = inputValue.match(/\[[^\[]*\]/); // the regex for [numberic_id]
if (userInputResult) {
userInput.value = inputValue.substring(0, [userInputResult.index - 1]); // -1 is to remove the space between the 'string' and the '[numeric_id]'
}
});
I should have mentioned that my input is also using Awesomplete (and jQuery). For this reason, binding normal events like keyup did not work (the event would fire whenever a user typed a key). I was able to achieve the functionality I wanted with the awesomplete-selectcomplete event as follows (this will add a hidden input element with value of the id from a string of the form "String [id]"):
$("#my-input").on('awesomplete-selectcomplete',function(){
var fullStr = this.value;
//alert(fullStr);
var regex = /\[[0-9]+\]/g;
var match = regex.exec(fullStr);
//alert(match[0]);
if (match != null) // match found for [id]
{
var fullName = fullStr.substr(0,fullStr.lastIndexOf("[")-1);
var x = match[0];
var id = x.substr(1, x.lastIndexOf("]")-1);
//alert(id);
$('#fwd-form').prepend('<input type="hidden" name="h_uid" value="' + id + '">');
$('#my-input').val(fullName);
}
});

Changing input box also need to find check box checked or not in JS

I have input box along with checkbox in table <td> like below,
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" id="summary" title="Check to set as Summary" />
</td>
Based on check box only the content of input box will be stored in DB.
In the JS file, I tried like
var updateComment = function( eventData )
{
var target = eventData.target;
var dbColumn = $(target).attr('data-db');
var api = $('#api').val();
var newValue = $(target).val();
var rowID = $(target).attr('data-id');
var summary = $('#summary').is(':checked');
params = { "function":"updatecomments", "id": rowID, "summary": summary };
params[dbColumn] = newValue;
jQuery.post( api, params);
};
$('.Comment').change(updateComment);
But the var summary always returning false.
I tried so many ways prop('checked'),(#summary:checked).val() all are returning false only.
How to solve this problem?
Looks like you have multiple rows of checkboxes + input fields in your table. So doing $('#summary').is(':checked') will return the value of first matching element since id in a DOM should be unique.
So, modify your code like this:
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" class="summary" title="Check to set as Summary" />
</td>
And, instead of $('#summary').is(':checked'); you can write like this:
var summary = $(target).parent().find(".summary").is(':checked');
By doing this, we are making sure that we are checking the value of checkbox with the selected input field only.
Update: For listening on both the conditions i.e. when when checking checkbox first and then typing input box and when first typing input box and then checked:
Register the change event for checkbox:
// Whenever user changes any checkbox
$(".summary").change(function() {
// Trigger the "change" event in sibling input element
$(this).parent().find(".Comment").trigger("change");
});
You have missed the jQuery function --> $
$('#summary').is(':checked')
('#summary') is a string wrapped in Parentheses. $ is an alias for the jQuery function, so $('#summary') is calling jquery with the selector as a parameter.
My experience is that attr() always works.
var chk_summary = false;
var summary = $("#summary").attr('checked');
if ( summary === 'checked') {
chk_summary = true;
}
and then use value chk_summary
Change all the occurrences of
eventData
To
event
because event object has a property named target.
And you should have to know change event fires when you leave your target element. So, if checkbox is checked first then put some text in the input text and apply a blur on it, the it will produce true.
Use like this
var summary = $('#summary').prop('checked');
The prop() method gets the property value
For more details, please visit below link.
https://stackoverflow.com/a/6170016/2240375

Use of parent and find to select an item in the DOM

I have this js to update a span value with a new value coming from some math.
$('.ammesso').blur(function(){
ammesso = $(this).val();
perc_worst ='<?php echo $az_info['perc_worst']; ?>';
if(isNaN(ammesso)){
console.log(ammesso);
}else{
flusso = ammesso*perc_worst/100;
var jsonObject = $.parseJSON(prevs);
console.log(prevs);
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text());
});
console.log('flusso calcolato: '+flusso);
}
});
The html is the following:
<fieldset>
<label>Ammesso: </label><input type="text" name="ammesso[0]" value="" class="ammesso numerico">
<label>Incassi previsti: </label>
<ul id="lista">
<li class="soff_grp">Value - <span class="cl393">CASH</span></li>
</ul>
</fieldset>
console.log('testo: '+$(this).parent('fieldset').find('.cl'+id_item).text()); should return what is now inside the span but I miss what is wrong and why I cannot select the span.
My assumptions are:
with .parent('fieldset') I come back to the first DOM element input
and span have in common
with .find('.cl'+id_item) I get the first element with that class
(that is present in the rendered HTML)
What is wrong in how I use this two selectors? As per what I understand of what I have read in the jQuery documentation it seems to me the right way to select it!
the context of input element is lost in each function. this refers to element in jsonObject on which you are iterating. You need to store the element context outside each loop and then use it in each function:
var fieldset = $(this).parent('fieldset');
$.each(jsonObject, function (i, obj) {
console.log(obj.id);
var id_item = obj.id;
//it gets the right value of 393
console.log('testo: ' + fieldset.find('.cl'+id_item).text());
});

Get the tag name of a form input value

How does one get the .tagName of a value passed in an HTML form input? This is to check whether the value that has been passed is an 'iFrame'. The input is to only accept iframes
For example:
//HTML
<input type="text" id="iFrame">
<button id="butt">Push</button>
//JavaScript
document.getElementById("butt").onclick = function(){
var iframe = document.getElementById("iFrame").value;
console.log(iframe.tagName);
}
I think you are looking for
var iframe = document.getElementsByTagName("iFrame")
I perhaps did not ask the question in the best way, initially.
I wanted to check if the value passed in the input field was an "iframe" (the input is to only accept iFrames). Since .value returns a string and not an HTML tag, getting the tag name through basic methods would not work. I needed another way.
For anybody else who needs a quick solution, this is how I managed to do it:
document.getElementById("submit").onclick = function(){
var iframe = document.getElementById("iFrame").value;
var check1 = iframe.match(/iframe/g);
var check2 = iframe.match(/frameborder/g);
var check3 = iframe.match(/http:/g);
var check = check1.length + check2.length + check3.length;
if (check === 4) {
alert("good!");
}
}

jQuery selector by form index and input name

Take the following page with two forms with different classes but each form has an input with the same name.
<form class='first_form'>
<input name='test' value='1' />
</form>
<form class='second_form'>
<input name='test' value='3'/>
</form>
I can get the form index and I know the name of the input but I do not know the index of the input.
Is there a way to chain a selector with the form index and the input name to get the value?
I have tried chaining but nothing seems to work
var inputName = 'test';
Var formIndex = 1;
$('*[name="' + inputName + '"]' +' ' + '$("form").eq(' + formIndex + ')').val();
FIDDLE
var formIndex=0;
var inputName="txtbox";
vall= $("form:eq("+ formIndex+") input[name= "+ inputName +" ]").val();
alert(vall);
your order was wrong
Untested, but could you do:
$('form:nth-of-type(1) input[name="test"]').val();
$("form:nth-child("+formIndex+") input[name='"+inputName+"']").val();
You could do in a more clever way:
var fieldName = 'test';
var formId = '.first_form'
$('form'+formId+' input[name='+fieldName+']).val()
Instead of index, use named selectors, like id or class. It will help you in the future find the correct form (when you will have more than 5, it will be hard to count witch one you are looking at :) )
But that is too complex:)
I would propose something like this:
var currentForm = $('form'+formId);
currentForm//here you can put a log into console if element has not been found and find that bug sooner.
currentForm.find('input[name='+fieldName+']').val()
You can access the form's element directly within the DOM using either of:
document.forms[formIndex]
document.forms[formName]
You can then reference an input element by name using:
document.forms[formIndex][inputName]
document.forms[formName][inputName]
Then just wrap it in $(...) to get yourself a jQuery collection. In your case:
var inputName = 'test',
formIndex = 1;
$(document.forms[formIndex][inputName]);
I imagine this is by far the most performant way, and it's readable too.
To add a little detail, document.forms is an HTMLCollection of all HTMLFormElements within a document. And given any HTMLCollection or HTMLFormElement you can access named elements within them as properties.

Categories

Resources