Javascript clearing comments of swear words - javascript

I am creating a comments board and via Javascript i am attempting to implement a piece of script which will prevent the user from submitting a paragraph if it has a undesirable word(s) in it. I have looked online and struggled to find any examples. This is what i have so far but not sure if i should be using index.of
index.php
<div class="askComment">
<h2>Submit new comment</h2>
<!--comment form -->
<form id="form" method="post">
<!-- need to supply post id with hidden fild -->
<input type="hidden" name="postid" value="<?php echo $post; ?>">
<input type="hidden" name="type" value="A">
<p>Hello <strong><?php echo $fname; ?></strong> what do you have to say</p>
<input type="hidden" name="fname" id="comment-name" value="<?php echo $fname; ?>" >
<input type="hidden" name="userid" id="comment-mail" value="<?php echo $UserId; ?>" >
<p>Your comment *</p>
<textarea name="comment" id="comment" cols="30" rows="10" placeholder="Type your comment here...." ></textarea>
<div id="error"></div>
<input type="submit" id="submit-comment" name="submit" value="Submit Comment">
</form>
</div>
mod_comment.php
$(document).ready(function () {
document.getElementById("submit-comment").disabled = true;
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").change(function () {
var comment = $("#comment").val();
if (comment.indexOf('????') === -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
} else {
document.getElementById("loginsubmit").disabled = false;
}
});
});

One possible solution (similar to your, same logic, just few changes/additions).
http://jsfiddle.net/pK7DK/
$("#submit-comment").attr('disabled', true);
var swear = new Array();
swear[0] = "jelly";
swear[1] = "trumpet";
swear[2] = "chocolate";
$("#comment").on("keyup", function () {
var comment = $("#comment").val();
word = comment.split(' ');
for (i = 0; i < word.length; i++) {
worda = word[i].trim();
worda = worda.replace(/\.|,|!|:| |;|\?|\r?\n/g, ''); // bad word + one of chars = bad word
console.log(worda);
if ($.inArray(worda, swear) != -1) {
$("#error").html('<font color="red">Please rewrite <strong>bad</strong> word found.</font>');
$("#submit-comment").attr('disabled', true);
break;
} else {
$("#error").html('');
$("#submit-comment").attr('disabled', false);
}
}
});
I would rather use 'keyup' event, so user will get error message(s) as he type. However - as mentioned, this can be easily overriden, server-side checking is a must.

Take a look at this: http://www.w3schools.com/jsref/jsref_search.asp (searches an array inside of an array);
It may not be the most optimal option, but it will be a start for your code.
EDIT: A better option (not the best, maybe) could be separating the comment string by words into an array and doing an intersection between the two arrays, here's a question explaining how to do intersections between arrays in js Simplest code for array intersection in javascript

Related

Auto Update Amount (USD) using onchange with javascript

I need help with this code. I have looked at tons of related questions but none has helped so far. Please help. These are exactly what I need:
To auto-update "Amount(USD)" once the value of "Amount(NGN)" is changed. Preferably with Vanilla Js.
I would also like to pick the final value of "Amount(USD)" and store in a PHP session to use in other pages.
See my code below:
<?php $grandTotal=10; ?>
<script type="text/javascript">
function calculateTotal() {
var nairaRate = document.pricecalculator.nairaRateToday.value; //get NGN rate today from admin and assign to nairaRate
dollarValue = eval(document.pricecalculator.nairaInput.value * nairaRate); //multiply nairaInput by nairaRate to get dollarValue
document.getElementById('dollar').innerHTML = dollarValue; //pass dollarValue to dollar to show auto-calculation onscreen
}
</script>
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" name="nairaInput" onchange="calculateTotal()" value="1" /> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
I was able to solve the problem like this:
<?php $grandTotal=10; ?> // set PHP variable
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC)</legend>
<label>Amount (NGN)</label><input type="number" id="naira-input" name="naira-input" onchange="calculateTotl()" value="1"/> <br />
<label>Amount (USD):</label><span id="dollar">1</span> <br />
</form>
<script type="text/javascript">
function calculateTotl() {
var nairaRate = document.getElementById("naira-input").value;
// Select your current input
let phpval = "<?= $grandTotal ?>"; // grab php value
var dollarResult = document.querySelector('#dollar');
var total = Number(nairaRate) * Number(phpval); evaluate current input * php value
return dollarResult.innerHTML = total; // write result to #dollar
}
</script>
Try this (worked for me):
var ngn = document.getElementById('ngn');
var dollar = document.getElementById('dollar');
ngn.onchange = ()=>{dollar.innerText=ngn.value*0.0026}
Check the following code. I have used a hardcoded value, that is 7 as nairaRate
let nairaInput = document.querySelector("input[name='NairaValue']")
nairaInput.addEventListener('change', (e) => calculateTotal(e.target.value, 7))
function calculateTotal(input, nairaRate) {
var resultInDollar = document.querySelector('#dollar');
var total = Number(input) / Number(nairaRate);
return resultInDollar.innerHTML = total
}
<form name="pricecalculator" action="">
<legend>Price Calculator (Buy BTC) Naira At 7</legend>
<label>Amount (NGN)</label><input type="number" name="NairaValue" onchange="calculateTotal()" value="0" /> <br />
<label>Amount (USD):</label><span id="dollar">0</span> <br />
<input type="hidden" name="nairaRateToday" value="<?= $grandTotal ?>">
</form>
Good Luck!

Keeping value of search box Javascript/HTML

I made a tool which make my work a little easier by inserting a value into a url in a new window on multiple sites. It was working quite well but now I am having the problem of the search value being cleared onsubmit.
Javascript:
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
if(document.search.website.checked) {
var website = open( "https://www.website.com/" + req, "website");
}
//--></script>
HTML:
<form name="search">
Please select the networks you want to use.
<p>
</center>
</p>
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
So far, return false had been working to keep the value of the input in the form="text" input name="query" but now it seems to clear it and reload the page. I'm not sure what changed.
You have errors in your code opening and closing the tags.
Try this code. It works:
<html>
<head></head>
<body>
Please select the networks you want to use
<div class="row">
<div class="column">
<br>
<input name="website" type="checkbox">Website to Search
<form name="text" onsubmit="run(); return false;">
<center>And enter your Query.</center>
<center>
<input name="query" placeholder="Steropodon" value="" size="50" type="TEXT">
<input value="Search" onclick="run()" type="BUTTON">
</center>
</form>
</div>
</div>
<script language="JAVASCRIPT">
function run() {
var request = document.text.query.value;
var req = "";
var endofurl = "endofurl.html";
for(var i = 0; i < request.length; i++) {
var ch;
if((ch = request.substring(i, i + 1)) == " ") req += " ";
else req += ch;
}
var checkbox = document.getElementsByName("website");
if(checkbox[0].checked) {
var website = open("https://www.website.com/" + req,
"website");
}
}
</script>
</body>
</html>
Hope it helps.
I fixed it. It was not the tags. I had only pasted a small amount of the total code to make it easier to read but I failed at making it easier to read. The problem was undefined inputs. I have been adding many if statements but didn't have a corrosponding checkbox. Oops.
Thanks for the help.

Javascript Validation (Input not showing after clicking Submit)

This is a simple code and I don't know where I went wrong.. Name validation works if no name is entered, but it doesn't show the result when a valid name is entered.
Here's my code:
I'm just new in html and javascript, hoping i'd get help from here. Thank you
function checkname(form) {
var eobj = document.getElementById('MITname');
var jname = form.Name.value;
var error = false;
eobj.innerHTML = '';
if (jname == '') {
error = "Name is required!";
var error2 = error.fontcolor("red");
}
if (error) {
if (hasFocus == false) {
form.Name.focus();
hasFocus = true;
}
eobj.innerHTML = error2;
return false;
}
return true;
}
function showinput() {
document.getElementById('namedisplay').innerHTML = document.getElementById('MITname').value;
}
function validate() {
hasFocus = false;
var form = document.forms['form'];
var ary = [checkname];
var rtn = true;
var z0 = 0;
for (var z0 = 0; z0 < ary.length; z0++) {
if (!ary[z0](form)) {
rtn = false;
}
}
return rtn;
}
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="submit" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Few issues here. (Also, welcome to Web Development!)
First, you never actually create the variable hasFocus. So you're never actually checking if it's true/false or not.
Second, where you create error2 means that it will only be accessible within the if() block it was created in. So, in the following if(error) block when you try to access it, it will return undefined.
Third, when you create error you are setting the value to false, which indicates a Boolean type, but then later setting its value to a String, which is definitely not a Boolean.
Fourth, the line var ary = [checkname]; is confusing to me. I get that you're trying to convert the name (from the input?) to an array, but that is not the way to do it. You can access each character of the name with string.charAt(index), so creating an array isn't really necessary.
Fifth, your validate() function as a whole is very confusing. I haven't a clue what you're trying to do. It looks like your teaching source may have mislead you, or you weren't paying attention that closely.
I could go on, however those (among other) issues are really making it difficult to find exactly what is going wrong, without digging too much into it. I don't want to write this for you, and so my suggestion would be to start again, and maybe checkout some more tutorials, perhaps from a different source. (Different youtube channel, etc.)
My problem is the validation. If I enter a blank name, an error message should appear next to the Name's text box indicating to enter a valid name.
<!DOCTYPE html>
<html>
<head>
<title>JAVASCRIPT FORM VALIDATION</title>
<script type="text/JavaScript">
function showMessage()
{
var Name = document.getElementById("Name").value;
displayname.innerHTML= Name;
var Email = document.getElementById("Email").value;
displayemail.innerHTML= Email;
var Website = document.getElementById("Website").value;
displaywebsite.innerHTML= Website;
var Comment = document.getElementById("Comment").value;
displaycomment.innerHTML= Comment;
var nameerror='';
var emailerror='';
var websiteerror='';
var commenterror='';
if (displayname.innerHTML=='')
{
nameerror = 'Please enter a valid name';
return false;
}
return true;
}
</script>
</head>
<body>
Name: <input type="text" id = "Name"> <span id = "nameerror"> </span>
<br></br>
Email: <input type="text" id = "Email">
<br></br>
Website: <input type="text" id = "Website">
<br></br>
Comnent: <textarea cols="35" rows="7" id="Comment"> </textarea>
<br></br>
<input type="submit" onclick="showMessage()" value="submit" />
<p>Name: <span id = "displayname"></span> </p>
<p>Email: <span id = "displayemail"></span> </p>
<p>Website: <span id = "displaywebsite"></span> </p>
<p>Comment: <span id = "displaycomment"></span> </p>
</body>
</html>
<form action="" name="form" onsubmit="return validate()">
<tr>
<td align="right">Name:<font color="red">*</font>
</td>
<td>
<input type="text" name="Name" /> <span id="MITname"> </span>
</td>
</tr>
<br/>
<input type="button" value="Submit" onclick="showinput()" />
<br/>
<label>Your input:</label>
<p><span id="namedisplay"></span>
</p>
</form>
Just remove type='submit' in your code it will submit your page while click once you click submit the data's are change to POST , So use button as type

Checking multiple files

I currently have a file element, and a button that allows a user to add more file elements so that if they wanted to, they could select multiple at once. I want to be able to loop through them and need some assistance as to what direction I should take or if there is a correct syntax to do this. Form, php, and JS code below.
Form:
<form action="<?php echo htmlspecialchars($_SERVER['PHP']);?>" method="post" enctype="multipart/form-data" name="upload_form" id="upload_form">
<br />
<input type="file" name="file[]" id="file"/>
<input id="addbutton" type="button" onclick = 'javascript: add()' value="ADD ANOTHER FILE" />
<br />
<input type="submit" id="submit" name="submit" value="SUBMIT" />
</form>
PHP:
if($_POST['submit'] == "SUBMIT")
{
$count = count($_FILES[ "file" ][ "tmp_name" ]);
echo $count;
for($i = 0; $i < $count; ++$i)
{
if($_FILES && $_FILES['file']['name'])
{
//code that does some stuff here
}
}
}
JS:
<script>
function add()
{
var form = document.getElementById("upload_form");
var addButton = document.getElementById('addbutton');
var br = document.createElement("br");
form.insertBefore(br, addButton);
form = document.getElementById("upload_form");
input = document.createElement("input");
input.type="file";
input.name="file[]";
form.insertBefore(input, addButton);
}
every thing is looks ok, u just need to add index to access particully uploaded file like
<?php
// ...
for($i = 0; $i < $count; ++$i)
{
echo $_FILES['file']['tmp_name'][$i];
// ...
Looks perfect, but you can just use this for multiple selection:
<input type="file" name="file[]" id="file" multiple="multiple" />
You won't need that javascript...

How to button enable when all textbox has value in jQuery?

I am new in programming. Here I have given description of my problem
I have one pair of two text box. One text box is for URL and other is for instruction but all text-boxes created dynamically depending on what value comes from database.
For example $testing_type_id=2 so I get total two pair of text boxes, let it called bundle. $i is used to identify textbox uniquely.
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
Here what I wanted to do that if all bundle has value, either in one textbox or both textbox so and so enable submit button. If I removed value so disable submit button using jQuery.
I think this will work
$(document).ready(function(){
$("input[class^='uploadtxt']").keyup(function(e){
var alltxt=$("input[class^='uploadtxt']").length;
var empty=true;
$("input[class^='uploadtxt']").each(function(i){
if($(this).val()=='')
{
empty=true;
$('#checkout').prop('disabled', true);
return false;
}
else
{
empty=false;
}
});
if(!empty) $('#checkout').prop('disabled', false);
});
});​
An example is here.
if($('.uploadtxt1').val() !='' && $('.uploadtxt2').val() !='')
{
$('#checkout').hide();
}
else
{
$('#checkout').show();
}
So assuming you want to show/ enable the button if the textareas / inputs have values. You could do something like this using jQuery.
$(window).ready(function(){
if( $('input, textarea').val().length >=0 ){
//run function to enable button
}
else if ( $('input, textarea').val().length <=0 ){
//run function to disable button
}
});
I think this is what you are sort of looking for. Let me know if I am way off or not understanding you correctly.
I am going to suggest a minor markup changes so that will be easy to handle the traversing.
Wrap the elements in a <div>
<div class="item">
<input type = "text" size="33" class="uploadtxt1 url" name="txturl_<?php echo $testing_type_id ; ?>" id = "txturl_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" />
<input type = "text" class="uploadtxt2" size="33" name="txtinstruction_<?php echo $testing_type_id ; ?>" id = "txtinstruction_<?php echo $testing_type_id; ?>_<?php echo $i ; ?>" value="" /> <br/>
<input type="submit" name="checkout" id="checkout" class="graybtn1 ptr button_float_left_checkout" disabled="disabled" value="Proceed To Checkout" />
</div>
Then, Attach a snippet on the change event
$("input[type=text]", $(".item")).change(function() {
var allField = true;
$(this).closest(".item").find("input[type=text]").each(function() {
allField = allField && ($(this).val().length > 0)
});
if(allField) {
$(this).closest(".item").find("input[type=submit]").prop('disabled', false);
}
});
Demo of Working Solution

Categories

Resources