user input to change a variable in a script - javascript

I'm using a widget on a web page but learning to code
this is the code i insert into my page:
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
</div>
one of the variables "data-room" i wish to change the value by way of user input. what script/code do i need in order to ask the user for the input and then replace the default value "meetingroom1"
Thanks

Let us say you have an input
<input id="myInput" type="text"/>
Add JS like following
$("#myInput").blur(function(){
$(".bistri-conference").data("room", $(this).val());
});

One approach, using plain JavaScript in this case, is as follows; first showing the HTML:
<!-- wrapping the <inputs> used to update the data in a <form> -->
<form action="#" method="post">
<!-- using <label> elements to allow clicking the text to
focus the relevant <input> -->
<label>Change the meeting room venue:
<!-- using a custom data-* attribute to
clearly denote the data to be
updated by the <input> element's value -->
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<!-- a <button> to trigger the updates: -->
<button type="button" id="update">Update</button>
</form>
<!-- your own posted element, unchanged -->
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12" data-chat="True"></div>
And the JavaScript:
function updateData() {
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
toUpdate = document.querySelector('.bistri-conference');
inputArray.forEach(function (input) {
if (input.value !== input.defaultValue) {
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
document.getElementById('update').addEventListener('click', updateData);
// a named function:
function updateData() {
// Using Function.prototype.call() to use
// Array.prototype.slice() to convert the NodeList
// returned by 'querySelectorAll()' to be converted
// into an Array:
var inputArray = Array.prototype.slice.call(this.form.querySelectorAll('input'), 0),
// retrieving the element to be updated by this function:
toUpdate = document.querySelector('.bistri-conference');
// iterating over the array of <input> elements, using
// Array.prototype.forEach():
inputArray.forEach(function(input) {
// the 'input' is the current array-element
// from the array over which we're iterating.
// if the value of the <input> is not the
// default-value of the <input>:
if (input.value !== input.defaultValue) {
// we update the data-* attribute of the
// element equivalent to the value held in
// the <input> element's 'data-attribute',
// setting it to the value entered in the <input>:
toUpdate.dataset[input.dataset.attribute] = input.value;
}
});
}
// binding the 'click' event-handler function (note the lack of
// of parentheses after the function's name) of the button:
document.getElementById('update').addEventListener('click', updateData);
label {
display: block;
}
div[data-room]::before {
content: 'current value: ' attr(data-room);
display: block;
}
div[data-room]::after {
content: 'current value: ' attr(data-capacity);
display: block;
}
<form action="#" method="post">
<label>Change the meeting room venue:
<input data-attribute="room" type="text" />
</label>
<label>Change the venue capacity:
<input data-attribute="capacity" type="text" />
</label>
<button type="button" id="update">Update</button>
</form>
<div class="bistri-conference" data-appid="hidenfromquestion" data-appkey="hiddenfromquestion" data-room="meetingroom1" data-capacity="10" data-media-controls="true" data-audio-codec="ISAC/16000" data-audio-birate="40" data-video-birate="400" data-device="320x240:12"
data-chat="True"></div>
JS Fiddle demo.
References:
Array.prototpe.forEach().
Array.prototype.slice().
document.getElementById().
document.querySelector().
document.querySelectorAll().
Function.prototype.call().
HTMLElement.dataset.
HTMLInputElement.

if you are looking something like this ... then try this ;)
<head>
<script type="text/javascript" src="https://api.bistri.com/bistri.conference.widget.js"></script>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function Onblur(event) {
var element=document.getElementById("something").value;
$(".bistri-conference").attr("data-room", element);
}
</script>
</head>
<body>
<div class="bistri-conference"
data-appid="hidenfromquestion"
data-appkey="hiddenfromquestion"
data-room="meetingroom1"
data-capacity="10"
data-media-controls="true"
data-audio-codec="ISAC/16000"
data-audio-birate="40"
data-video-birate="400"
data-device="320x240:12"
data-chat="True">
<input type="text" id="something" onblur="javascript:Onblur(event)" value="Text field" />
</div>
</body>

Related

How to include user input in the html string of a some parent DOM element?

I want to store the content of a div container in windows history, by running the following line:
window.history.pushState($('#myDivId').html(), "title", 'some url');
I would later use this info when user presses the back button.
Problem:
User has a form to fill, with one input. User types his name (say John) and clicks on submit. The onSubmit function is triggered and here I get the html content of parent div and store it in history object. The problem is, user input (John) in this example, is not captured.
The following screenshot shows the output of my script below:
Code Snippet
function onSubmit() {
var str = $('#myDivId').html();
alert("this goes to windows history: " + str);
// window.history.pushState($('#myDivId').html(), "title", 'some url');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="onSubmit()">
<div id="myDivId">
First name: <input id="firstNameId" type="text" name="FirstName" value=""><br>
<input type="submit" value="submit">
</div>
</form>
How can include user input in the str before pushing it in the history?
Update:
This is a simplified example, in the real scenario I have several input fields in the container. So I am looking for a way to capture all the input values through the container.
The value attribute represents the default value of the field, not the current value.
There is no HTML attribute which reflects that.
If you want to store it, then you need to store it explicitly.
I'd approach this by using serializeArray() (and converting it to JSON to store in the history), and then looping over it to restore the data to the form.
Here I'm using a delegate event to set value property as value attribute
function onSubmit() {
var str = $('#myDivId').html();
alert("this goes to windows history: " + str);
// window.history.pushState($('#myDivId').html(), "title", 'some url');
}
$(document).on('input', '.attr-input', function() {
$(this).attr('value', this.value)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="onSubmit()">
<div id="myDivId">
First name: <input id="firstNameId" class="attr-input" type="text" name="FirstName" value=""><br>
<input type="submit" value="submit">
</div>
</form>
I am not clear what you are asking. I have provided a solution as per my understanding.
function onSubmit() {
$("#firstNameId").attr('value', $("#firstNameId").val())
var str = $('#myDivId').html();
alert("this goes to windows history: " + str);
// window.history.pushState($('#myDivId').html(), "title", 'some url');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="onSubmit()">
<div id="myDivId">
First name: <input id="firstNameId" type="text" name="FirstName" value=""><br>
<input type="submit" value="submit">
</div>
</form>

Create Custom validation Class in javaScript/Jquery

Let say there is an input element field and i want to create a new validation class myClass ,that i can insert with any html element that might performing some function and also setting attribute such as
readonly="true"
required='true'.
HTML is
<td>
<input type="text" id="endDate" name ="endDate" class="select_200" required readonly="true">
</td>
Now rather setting elements separately need one class for performing:
A function check "let say character count less then 10" and setting
attribute.
Setting attributes such as readonly ,required
So that i can add that class to all elements with similar property.
Validation + Setting/ Reseting attributes by adding class only
You can set your own custom attributes for your input elements and use those custom attributes to query the input fields and perform various actions. You can find my sample below.
$(function () {
//Set various input field attributes here
$("input[data-myCustomClass]").each(function(){
//$(this).attr("readonly", true);
$(this).attr("required", true);
});
//Sets max length - you can change this code to retrieve info from attribute
$("input[data-setFieldLength]").each(function(){
$(this).attr("maxlength", 10);
});
//Validate for field length based on "validateFor" attribute
$("input[data-validateFieldLength]").each(function(){
$(this).on('focusout', function(){
var validateFor = $(this).attr("validateFor");
if ($.trim($(this).val()).length < parseInt(validateFor))
{
$(this).focus();
$(this).select();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input type="text" data-myCustomClass data-setFieldLength id="field1" />
<input type="text" data-myCustomClasss id="field2" />
<input type="text" data-setFieldLength id="field3" /> <!-- set field length to 10 -->
<input type="text" data-validateFieldLength id="field4" validateFor="5" /> <!-- validate for 5 characters and return focus -->
you have create new function for a field?
on
<form onsubmit="return validate()" name="form">
<td>
<input type="text" id="custname" name ="endDate" class="select_200"
required readonly="true">
<font style="color:red" id="custnameerror"></font>
</td>
<button onclick="return validate()"></button>
</form>
javascript validation function like
<script type="text/javascript">
function validate(from)
{
var error=document.getElementById("custnameerror");
var custname=form["custname"].value;
error.innerHTML="";
if( custname==null || custname==""){
error.innerHTML="Enter customer name";
return false;
}
if(custname.length<3){
error.innerHTML="Customer name should be minimum 3 character";
return false;
}
if(custname.length>80){
error.innerHTML="Customer name should be in between 3 to 80
character";
return false;
}/*end */
</script>

Why doesn't empty() work on input in search bar?

When clicking theinviteButton, the input search bar should clear out, but it doesn't work with my current code.
Am I targeting the element incorrectly?
$("#inviteButton").click(function(){
var userName = $("#searchUser").val();
if (userName.trim() != "") {
if (userName == myUserName) {
$("#connectToBox").append("You can't invite yourself");
$("#searchUser").empty(); // Doesn't work
} else {
socket.emit("checkUserConnect", userName, function(data){
if (data.result === undefined) {
console.log("No name");
$("#connectToBox").append("User does not exist");
$("#searchUser").empty(); // Doesn't work
} else {
console.log("name exists");
$("#searchUser").empty(); // Doesn't work
$("#connectToBox").append("Invite send");
UserID = data.result.id;
socket.emit("connectToUser", myUserName, UserID, currentConversation);
}
});
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="connectToBox">
<label for="search-2">Type in username</label>
<input type="search" name="search-2" id="searchUser" value="">
Connect
</div>
To empty an input field you would normally use:
$('#searchUser').val('')
Empty is used to clear away child nodes from elements like divs or p tags, but not for inputs.
Reason for that is that the text within an input is not represented as a child node of the element and instead stored on an html attribute of the input tag. Hence .empty() does not work for clearing the value.
You can clear the input field by using
$('#searchUser').val('');
$('#searchUser').val('');
This will work fine according to your application.
The empty() method removes all child nodes and content from the selected elements. Src: W3Schools
According to your requirement you need to reset the value of an input field, for that we have val() function. You can assign an empty string and it will work fine.
Using empty() won't work here.
Check these examples -
empty() working correctly -
function emptyOperation(){
$("div").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
empty() as per your code [won't work] -
function emptyOperation(){
$("#input-field").empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>
Solution to your problem -
function emptyOperation(){
$("#input-field").val('');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" id="input-field" value="Random string">
</div>
<button onclick="emptyOperation()">Check</button>

How to get span element with no id which is inside a div with no id

I have 2 span elements inside 2 div elements. Both span elements have no id and both div elements also have no id.
The 1st div has the 1st input element with an id (id_name) and then have the 1st span element after it.
The 2nd div has the 2nd input element with an id (id_password) and then have the 2nd span element after it.
I have a javascript function which I call on submit of form. Inside that function I can get the 1st input element in a variable element_id_name and the 2nd input element in a variable element_id_password. Now how can I get the 1st span element which comes after 1st input element? And how can I get the 2nd span element which comes after 2nd input element? Since I dont have id for span elements, I cannot use document.getElementById(). Is there a way to get 1st span element by reference to 1st input element?
This is my code:
<html>
<head>
<meta charset="ISO-8859-1">
<title>test</title>
<style type="text/css">
.error_noshow{
display: none;
}
.error_show{
color: red;
}
</style>
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
return false;
}
</script>
</head>
<body>
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
</body>
</html>
Thank you for reading my question.
var spans = document.getElementsByTagName('span');
span[0] is the first span, span[1] is the second span. However it's not the preferred way to do this. Use jQuery to make it easier or add an id or classname
To access next span element you can use nextElementSibling property.
<script type="text/javascript">
function validate() {
var element_id_name = document.getElementById("id_name");
var element_id_password = document.getElementById("id_password");
var firstSpan=element_id_name.nextElementSibling;
return false;
}
</script>
But keep in mind that nextElementSibling not working in all version of browsers so you can simulate this using nextSibling http://www.w3schools.com/dom/prop_node_nextsibling.asp;
You can use querySelector to find the elements by their attributes.
function validate() {
var element_id_name = document.querySelector("[name=txt_user_name]");
var element_id_password = document.querySelector("[name=txt_password]");
console.log(element_id_name, element_id_password);
return false;
}
.error_noshow{
display: none;
}
.error_show{
color: red;
}
<form id="form_login" method="post" action="" onsubmit="validate();">
<div>
<label for="id_name">User Name:</label>
<input type="text" id="id_name" name="txt_user_name">
<span class="error_noshow">Required field</span>
</div>
<div>
<label for="id_password">Password:</label>
<input type="password" id="id_password" name="txt_password">
<span class="error_noshow">Required field</span>
</div>
<button type="submit">Submit</button>
</form>
I'm not answering the question because someone already did, but it seems like you want to check if the user typed something in both field, you could skip the javascript and use the HTML5 tag "required" like so
<input type="text" require />.
The user will have an error message if he tries to submit. But keep in mind that old version of IE will skip this check.

Get input value into a <form> inline

Following my code:
<script>
function getText(text){
alert(text);
}
</script>
<form action="getText(/*here function for get text*/)">
<input type="text" class="text"/>
<input type="submit"/>
<div></div>
</form>
How to get textarea value with pure javascript in the <form> where indicated?
The action attribute contains the URL that the form will be submitted to, not JavaScript.
If you want to process the form data with JavaScript, then bind a submit event handler to it. This will be fired in the context of the form, so you can access the form element via this.
You can access the form controls through the elements collection. They will have value properties containing their values.
<form action="/some/handler" id="myForm">
<textarea name="myTextArea" class="text"></textarea>
<input type="submit">
<div></div>
</form>
<script>
function getText(text){
alert(text);
}
function formSubmitHandler(evt) {
var textarea = this.elements.myTextArea;
getText(textarea.value);
}
document.getElementById('myForm').addEventListener('submit', formSubmitHandler);
</script>
You may wish to call evt.preventDefault() if you are going to handle the form processing entirely with JS (when JS is available).
If you want value from input without using selector, then you can use some thing like this,
but remember, the value your are getting from input tag should be used as a first child of form element.
<form action="">
<input type="text" class="text"/>
<input type="button" onclick="getText()" value="get value">
<div></div>
</form>
<script>
function getText(text){
var textValue = document.getElementsByTagName('input')[0].value;
alert(textValue);
}
</script>
EDIT
If you want the text from input value after pressed the enter key then you could do like this.
<form action="">
<input type="text" class="text" onkeydown="getText(event)"/>
<div></div>
</form>
<script>
function getText(event){
var textValue = document.getElementsByTagName('input')[0].value;
if(event.which == 13){
alert(textValue);
}
}
</script>
Here a little function for you
function getTextAreaByClass(lookFor) {
var i; /* I always define at the top so jslint doesn't carp */
var elems = document.getElementsByTagName("textarea");
for (i in elems) {
if((' '+elems[i].className+' ').indexOf(' '+lookFor+' ') > -1) {
return elems[i].innerHTML;
}
}
return ""; /* or return false or whatever else you want to denote not found */
}
The above will search through all the textarea tags, look for a class that matches and will return the content within the textarea.

Categories